package com.xbongbong.saas.service.impl;/*/*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.outLink.domain.entity.OuterLinkConfigEntity;
import com.xbongbong.outLink.domain.entity.OuterLinkEntity;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OuterLinkAddRemoveAttrEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.FormExplainHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.help.analysis.data.FormDataAllListAnalysisDataHelp;
import com.xbongbong.paas.help.service.impl.FormDataLinkDataUpdateGetServiceImpl;
import com.xbongbong.paas.lowcode.CustomButtonService;
import com.xbongbong.paas.lowcode.LowCodeConfigService;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.outerlink.OuterLinkRegistry;
import com.xbongbong.paas.outerlink.interfaces.PaasOuterLinkConfigService;
import com.xbongbong.paas.pojo.ButtonExtraPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.OutLinkFieldAttrEntity;
import com.xbongbong.paas.pojo.UserSimpPojo;
import com.xbongbong.paas.pojo.dto.ColumnSetListDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkAddDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkAddGetDTO;
import com.xbongbong.paas.pojo.dto.OuterLinkAppearanceGetDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.StartProcessDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.ColumnSetListVO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateGetVO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.MyPendingDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.pojo.vo.StartProcessVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.service.impl.WorkOrderDataFormDataServiceImpl;
import com.xbongbong.paas.service.impl.base.BaseFormDataService;
import com.xbongbong.paas.service.workflow.trigger.WorkflowFormDataOperationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.FormDataAddFormExplainHandlerName;
import com.xbongbong.parent.explain.FormDataFormExplainHandleName;
import com.xbongbong.parent.explain.FormDataListFormExplainHandleName;
import com.xbongbong.parent.explain.FormDataUpdateGetExplainHandler;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataLinkDataGetServiceImpl;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataUpdateGetAnalysisDataHelp;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.custombutton.pojo.dto.CustomButtonListDTO;
import com.xbongbong.pro.custombutton.pojo.vo.CustomButtonListVO;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.lowcode.ButtonTypeEnum;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.lowcodeconfig.pojo.dto.LowCodeConfigGetDTO;
import com.xbongbong.pro.lowcodeconfig.pojo.vo.LowCodeConfigGetVO;
import com.xbongbong.pro.outLink.pojo.OuterLinkAppearanceGetVO;
import com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.pro.workorder.pojo.WorkOrderCenterDataDetailPojo;
import com.xbongbong.pro.workorder.pojo.WorkOrderCenterSecondTitlePojo;
import com.xbongbong.pro.workorder.pojo.WorkOrderDataFormPojo;
import com.xbongbong.pro.workorder.pojo.WorkOrderNodeInfoPojo;
import com.xbongbong.pro.workorder.pojo.WorkOrderProcessPojo;
import com.xbongbong.pro.workorder.pojo.dto.WorkOrderDataDetailDTO;
import com.xbongbong.pro.workorder.pojo.dto.WorkOrderMyPendingDTO;
import com.xbongbong.pro.workorder.pojo.dto.WorkOrderProgressDTO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataDetailVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderMyPendingVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderProcessNodeV0;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderProcessOperateVO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderProcessVO;
import com.xbongbong.process.operate.ProcessFieldHelp;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.workorder.WorkOrderProcessConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTagEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.ListBatchEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OutLinkSettingTypeEnum;
import com.xbongbong.saas.enums.OuterLinkTypeEnum;
import com.xbongbong.saas.enums.SaasBatchEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SaasSubButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.WorkOrderStageOperationEnum;
import com.xbongbong.saas.enums.WorkOrderStageRobTypeEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.dictionary.WorkOrderShipStatusEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.help.FormatProductHelp;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.help.SaasAddHelp;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.WorkOrderListDataPermissionHelp;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.WorkOrderCcModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderTagModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.FormDataDraftService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WorkOrderFormDataService;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.TimeUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserConfigModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workorder.explain.WorkOrderFormDataFormExplainHandleName;
import com.xbongbong.workorder.service.WorkOrderFlowUserService;
import com.xbongbong.workorder.service.WorkOrderStageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 * @date 2019/3/20 10:52
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderFormDataService")
public class WorkOrderFormDataServiceImpl extends BaseFormDataService implements WorkOrderFormDataService {
    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderFormDataServiceImpl.class);

    @Resource
    private OuterLinkRegistry outerLinkRegistry;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private WorkOrderFormDataFormExplainHandleName workOrderFormDataFormExplainHandleName;
    @Resource
    private FormDataDraftService formDataDraftService;
    @Resource
    private SaasAddHelp saasAddHelp;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private ProModelService proModelService;
    @Resource
    private FormatProductHelp formatProductHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private FormExplainHelp formExplainHelp;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private UserHelp userHelp;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private FormDataLinkDataUpdateGetServiceImpl formDataLinkDataUpdateGetService;
    @Resource
    private FormDataLinkDataGetServiceImpl formDataLinkDataGetServiceImpl;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private FormDataListFormExplainHandleName formDataListFormExplainHandleName;
    @Resource
    private WorkOrderStageService workOrderStageService;
    @Resource
    private UserModel userModel;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private WorkOrderListDataPermissionHelp workOrderListDataPermissionHelp;
    @Resource
    private WorkOrderTagModel workOrderTagModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WorkOrderFlowUserService workOrderFlowUserService;
    @Resource
    private ProEsHelper proEsHelper;
    @Resource
    private WorkOrderFormService workOrderFormService;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private FormDataUpdateGetAnalysisDataHelp formDataUpdateGetAnalysisDataHelp;
    @Resource
    private FormDataFormExplainHandleName formDataFormExplainHandleName;
    @Resource
    private FormDataAddFormExplainHandlerName formDataAddFormExplainHandlerName;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private CommonHelp commentHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private FormDataAllListAnalysisDataHelp formDataAllListAnalysisDataHelp;
    @Resource
    private UserConfigService userConfigService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private WorkOrderCcModel workOrderCcModel;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasOuterLinkConfigService outerLinkConfigService;
    @Resource
    private ProcessFieldHelp processFieldHelp;
    @Resource
    private WorkOrderDataFormDataServiceImpl workOrderDataFormDataService;
    @Resource
    private CustomButtonService customButtonService;
    @Resource
    private LowCodeConfigService lowCodeConfigService;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private WorkflowFormDataOperationService workflowFormDataOperationService;
    @Resource
    private FormDataUpdateGetExplainHandler formDataUpdateGetExplainHandler;
    @Resource
    private RichTextService richTextService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataAddGetVO addGet(FormDataAddGetDTO formDataAddGetDTO) throws XbbException {
        FormDataAddGetVO formDataAddGetVO = new FormDataAddGetVO();
        try {
            Long formId = formDataAddGetDTO.getFormId();
            String corpid = formDataAddGetDTO.getCorpid();

            //从工单全部列表新建，默认使用第一个工单模板
            List<WorkOrderFormEntity> workOrderFormList = workOrderFormService.getTemplateWithPermission(formDataAddGetDTO.getLoginUser(), formDataAddGetDTO.getAppId(), null);
            if (Objects.equals(formId, 0L)) {
                formId = workOrderFormList.get(0).getId();
            }
            LowCodeConfigGetDTO lowCodeConfigGetDTO = new LowCodeConfigGetDTO();
            lowCodeConfigGetDTO.setCorpid(corpid);
            lowCodeConfigGetDTO.setFormId(formId);
            lowCodeConfigGetDTO.setBusinessType(formDataAddGetDTO.getBusinessType());
            lowCodeConfigGetDTO.setLoginUser(formDataAddGetDTO.getLoginUser());
            lowCodeConfigGetDTO.setType(ButtonTypeEnum.ADD.getCode());
            LowCodeConfigGetVO lowCodeConfig = lowCodeConfigService.get(lowCodeConfigGetDTO);
            formDataAddGetVO.setLowCodeConfig(lowCodeConfig);
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
            if (Objects.isNull(workOrderFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            // TODO: 2019/4/11  setPaasFormEntity到底有何神奇之处
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            formDataAddGetVO.setPaasFormEntity(paasFormEntityExt);
            if (formDataAddGetDTO.getFormId() == null) {
                formDataAddGetDTO.setFormId(workOrderFormEntityExt.getId());
            }

            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(workOrderFormEntityExt.getId(), corpid);
            if (Objects.isNull(workOrderExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataAddGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
            HandlerExplainVO handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            if (handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainList = handlerExplainVO.getHeadList();
            // 设置默认的关联数据
            paasFormHelp.setDefaultLinkData(explainList, formDataAddGetDTO, handlerExplainVO);
            //工单如果是自由流程，负责人字段显示并必填，指定流程不显示
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
            boolean isFree = Objects.equals(workOrderTemplateEntity.getIsFree(), 1);

            String serialNo = "";
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                // 获取流水号
                if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.SERIALNO.getType()) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ZERO)) {
                    serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
                }
                if (!isFree) {
                    //指定流程。设置负责人不可见
                    if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.USER.getType())
                            && Objects.equals(WorkOrderEnum.MANAGER_ID.getAttr(), fieldAttrEntity.getAttr())) {
                        fieldAttrEntity.setVisible(0);
                    }
                }
            }

            formDataAddGetVO.setSerialNo(serialNo);
            // 新建工单时某些字段赋初始值
            FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
            BeanUtil.copyProperties(formDataAddGetDTO, formatExplainDTO);

            /*
            * 工单模板选择，动态渲染，模拟解释的方式实现，不刷在解释里
            * start
            * */
//            List<WorkOrderFormEntity> workOrderFormList = workOrderFormService.getTemplateWithPermission(formDataAddGetDTO.getLoginUser(), formDataAddGetDTO.getAppId(), null);
            FieldAttrEntity templateFieldAttrEntity = new FieldAttrEntity();
            if (workOrderFormList != null && workOrderFormList.size() == 1) {
                templateFieldAttrEntity.setVisible(0);
            } else {
                templateFieldAttrEntity.setVisible(1);
            }
            templateFieldAttrEntity.setAttrName(OperateModuleTypeEnum.WORK_ORDER.getName());
            templateFieldAttrEntity.setAttr(FieldTypeEnum.TEMPLATE.getAlias());
            templateFieldAttrEntity.setAttrType(FieldTypeEnum.TEMPLATE.getEsalias());
            templateFieldAttrEntity.setFieldType(FieldTypeEnum.TEMPLATE.getType());
            templateFieldAttrEntity.setEditable(1);
            templateFieldAttrEntity.setComboType(0);
            templateFieldAttrEntity.setDefaultAttr(new DefaultAttrPoJo());
            List<ItemPoJo> templateItem = new ArrayList<>();
            for (WorkOrderFormEntity entity : workOrderFormList) {
                ItemPoJo itemPoJo = new ItemPoJo();
                itemPoJo.setValue(entity.getId());
                itemPoJo.setText(entity.getName());
                if (Objects.equals(entity.getId(), formId)) {
                    itemPoJo.setChecked(true);
                }
                templateItem.add(itemPoJo);
            }
            templateFieldAttrEntity.setItems(templateItem);
            explainList.add(0, templateFieldAttrEntity);
            /*end*/

            formatExplainDTO.setExplainList(explainList);
            saasAddHelp.formatExplain(formatExplainDTO);
            formDataAddGetVO.setExplainList(formatExplainDTO.getExplainList());
            // saas特殊返回字段，放在一个对象中
            saasAddHelp.formatSaasAttrToReturn(formDataAddGetVO, formDataAddGetDTO);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.addGet workOrderFrom 数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddGetVO;
    }

    /**
     * Description: 外链在新建时，返回初始化字段属性和数据（流水号等）
     * @param outerLinkAddGetDTO
     * @return com.xbongbong.paas.pojo.vo.FormDataAddGetVO
     * @throws XbbException XbbException
     * @author 曹远远
     * @date
     * @since v1.0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public FormDataAddGetVO addGetForOutLink(OuterLinkAddGetDTO outerLinkAddGetDTO) throws XbbException {
        FormDataAddGetVO formDataAddGetVO = new FormDataAddGetVO();
        try {
            OuterLinkEntity outerLinkEntity = outerLinkRegistry.getByToken(outerLinkAddGetDTO.getToken(),OuterLinkTypeEnum.WRITE.getCode());
            String corpid =outerLinkEntity.getCorpid();
            Long formId = outerLinkEntity.getFormId();
            Integer businessType = outerLinkEntity.getBusinessType();

            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
            if (Objects.isNull(workOrderFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            // TODO: 2019/4/11  setPaasFormEntity到底有何神奇之处
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            formDataAddGetVO.setPaasFormEntity(paasFormEntityExt);

            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(workOrderFormEntityExt.getId(), corpid);
            if (Objects.isNull(workOrderExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);

            // 获取字段解释信息，根据权限设置过滤不可见字段 start
            ExplainUtil.filterSpecialAttr(explainList, OuterLinkTypeEnum.WRITE.getCode(), null);
            // 过滤各业务特殊字段
            List<String> attrList = OuterLinkAddRemoveAttrEnum.getAttrList(businessType);
            if (CollectionsUtil.isNotEmpty(attrList)) {
                explainList.removeIf(item -> attrList.contains(item.getAttr()));
            }
            explainList.forEach(item -> {
                item.setVisible(1);
                item.setEditable(1);
                item.setVisibleScopeEnable(0);
                item.setEditableAdvanceEnable(0);
                if (ExplainUtil.isSubFormNoSelectProduct(item.getFieldType())){
                    List<? extends FieldAttrEntity> subExplainList = item.getSubForm().getItems();
                    for (FieldAttrEntity subAttrEntity : subExplainList) {
                        subAttrEntity.setVisible(1);
                        subAttrEntity.setEditable(1);
                        subAttrEntity.setVisibleScopeEnable(0);
                        subAttrEntity.setEditableAdvanceEnable(0);
                    }
                    item.getSubForm().setItems(subExplainList);
                }
            });
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            handlerExplainDTO.setCorpid(corpid);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
            HandlerExplainVO handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            if (handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainList = handlerExplainVO.getHeadList();
            OuterLinkConfigEntity outerLinkConfigEntity = outerLinkConfigService.getOuterLinkConfigEntities(corpid,formId,OuterLinkTypeEnum.WRITE.getCode(), OutLinkSettingTypeEnum.PERMISSION_SETTING.getCode());
            List<String> notVisableAttr = new ArrayList<>();
            List<String> notEditableAttr = new ArrayList<>();
            Map<String,List<String>> notVisiableSubAttrMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String,List<String>> notEditableSubAttrMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(outerLinkConfigEntity)){
                String explains = outerLinkConfigEntity.getExplains();
                List<OutLinkFieldAttrEntity> outLinkFieldAttrEntities = JSONArray.parseArray(explains,OutLinkFieldAttrEntity.class);
                for (int i = 0; i < outLinkFieldAttrEntities.size(); i++) {
                    OutLinkFieldAttrEntity entity = outLinkFieldAttrEntities.get(i);
                    //  子表单内不可见字段
                    List<String> notVisiableSubAttrList = new ArrayList<>();
                    List<String> notEditableSubAttrList = new ArrayList<>();
                    if (ExplainUtil.isSubFormNoSelectProduct(entity.getFieldType())){
                        if(Objects.isNull(entity.getSubForm())){
                            continue;
                        }
                        List<OutLinkFieldAttrEntity> subExplainList = JSONObject.parseArray(JSON.toJSONString(entity.getSubForm().getItems()), OutLinkFieldAttrEntity.class);
                        subExplainList.forEach(item -> {
                            if (!Objects.equals(item.getVisible(),1)){
                                notVisiableSubAttrList.add(item.getAttr());
                            }
                            if (!Objects.equals(item.getEditable(),1)){
                                notEditableSubAttrList.add(item.getAttr());
                            }
                        });
                        notVisiableSubAttrMap.put(entity.getAttr(),notVisiableSubAttrList);
                        notEditableSubAttrMap.put(entity.getAttr(),notEditableSubAttrList);
                    }
                    if (!Objects.equals(entity.getVisible(),1)){
                        notVisableAttr.add(entity.getAttr());
                    }
                    if (!Objects.equals(entity.getEditable(),1)){
                        notEditableAttr.add(entity.getAttr());
                    }
                }
            }
            Iterator it = explainList.iterator();
            while (it.hasNext()){
                FieldAttrEntity fieldAttrEntity = (FieldAttrEntity) it.next();
                if (notVisableAttr.contains(fieldAttrEntity.getAttr())){
                    // 字段不可见 直接remove
                    it.remove();
                    continue;
                }
                if (notEditableAttr.contains(fieldAttrEntity.getAttr())){
                    fieldAttrEntity.setEditable(0);
                }
                if (ExplainUtil.isSubFormNoSelectProduct(fieldAttrEntity.getFieldType())){
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    List<String> notVisiableSubAttrList = notVisiableSubAttrMap.getOrDefault(fieldAttrEntity.getAttr(),new ArrayList<>());
                    if (Objects.equals(fieldAttrEntity.getSaasAttr(), WorkOrderEnum.CONTACT_INFORMATION.getSaasAttr())) {
                        // 外链填写，如果电话字段不可见，不能romve，而是设置visiable为o
                        subExplainList.forEach(item -> {
                            if (notVisiableSubAttrList.contains(item.getAttr())){
                                item.setVisible(0);
                            }
                        });
                    } else {
                        subExplainList.removeIf(item -> notVisiableSubAttrList.contains(item.getAttr()));
                    }
                    List<String> notEditableSubList = notEditableSubAttrMap.getOrDefault(fieldAttrEntity.getAttr(),new ArrayList<>());
                    subExplainList.forEach(item -> {
                        if (notEditableSubList.contains(item.getAttr())){
                            item.setEditable(0);
                        }
                    });
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
            }
            // 显示设置 替换attrName
            Map<String,String> namedMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String,String> namedSubMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            OuterLinkConfigEntity configEntity = outerLinkConfigService.getOuterLinkConfigEntities(corpid,formId,OuterLinkTypeEnum.WRITE.getCode(),OutLinkSettingTypeEnum.DISPLAY_SETTING.getCode());
            if (Objects.nonNull(configEntity)){
                String explains = configEntity.getExplains();
                List<OutLinkFieldAttrEntity> outLinkFieldAttrEntities = JSONArray.parseArray(explains,OutLinkFieldAttrEntity.class);
                for (int i = 0; i < outLinkFieldAttrEntities.size(); i++) {
                    OutLinkFieldAttrEntity entity = outLinkFieldAttrEntities.get(i);
                    if (ExplainUtil.isSubFormNoSelectProduct(entity.getFieldType())){
                        List<? extends OutLinkFieldAttrEntity> subExplainList = entity.getSubForm().getItems();
                        if (Objects.nonNull(subExplainList)){
                            for (int j = 0; j < subExplainList.size(); j++) {
                                OutLinkFieldAttrEntity value = subExplainList.get(j);
                                if (Objects.equals(value.getRenamed(),1)){
                                    namedSubMap.put(entity.getAttr() + "." + value.getAttr(),value.getDefaultName());
                                }
                            }
                        }
                    }
                    if (Objects.equals(entity.getRenamed(),1)){
                        namedMap.put(entity.getAttr(),entity.getDefaultName());
                    }
                }
                if (StringUtil.isNotEmpty(configEntity.getDefaultFormName()) ){
                    paasFormEntityExt.setName(configEntity.getDefaultFormName());
                }
            }
            for (int i = 0; i < explainList.size(); i++) {
                FieldAttrEntity fieldAttrEntity = explainList.get(i);
                if (ExplainUtil.isSubFormNoSelectProduct(fieldAttrEntity.getFieldType())){
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    if (Objects.nonNull(subExplainList)){
                        for (int j = 0; j < subExplainList.size(); j++) {
                            FieldAttrEntity fieldAttr = subExplainList.get(j);
                            if (namedSubMap.containsKey(fieldAttrEntity.getAttr() + "." + fieldAttr.getAttr())){
                                fieldAttr.setAttrName(namedSubMap.getOrDefault(fieldAttrEntity.getAttr() + "." + fieldAttr.getAttr(),""));
                            }
                        }
                    }
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                if (namedMap.containsKey(fieldAttrEntity.getAttr())){
                    fieldAttrEntity.setAttrName(namedMap.getOrDefault(fieldAttrEntity.getAttr(),""));
                }
            }

            //工单如果是自由流程，负责人字段显示并必填，指定流程不显示
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
            boolean isFree = Objects.equals(workOrderTemplateEntity.getIsFree(), 1);

            String serialNo = "";
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
                if (!isFree) {
                    //指定流程。设置负责人不可见
                    if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.USER.getType())
                            && Objects.equals(WorkOrderEnum.MANAGER_ID.getAttr(), fieldAttrEntity.getAttr())) {
                        fieldAttrEntity.setVisible(0);
                    }
                }
            }

            formDataAddGetVO.setSerialNo(serialNo);
            // 新建工单时某些字段赋初始值
            FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
            formatExplainDTO.setBusinessType(businessType);
            formatExplainDTO.setCorpid(corpid);

            formatExplainDTO.setExplainList(explainList);
            saasAddHelp.formatExplain(formatExplainDTO);
            formDataAddGetVO.setExplainList(formatExplainDTO.getExplainList());

            OuterLinkAppearanceGetDTO outerLinkAppearanceGetDTO = new OuterLinkAppearanceGetDTO();
            outerLinkAppearanceGetDTO.setCorpid(corpid);
            outerLinkAppearanceGetDTO.setFormId(formId);
            OuterLinkAppearanceGetVO appearance = outerLinkConfigService.getAppearance(outerLinkAppearanceGetDTO);
            JSONObject appearanceObj = new JSONObject();
            appearanceObj.put("themeList", appearance.getThemeList());
            appearanceObj.put("configInfo", appearance.getConfigInfo());
            appearanceObj.put("initFlag", appearance.getInitFlag());
            formDataAddGetVO.setOuterLinkAppearance(appearanceObj);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.addGet workOrderFrom 数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddGetVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataAddVO add(FormDataAddDTO formDataAddDTO) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        WorkOrderEntity workOrderEntity = new WorkOrderEntity();
        String corpid = formDataAddDTO.getCorpid();
        try {
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formDataAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            String userId = formDataAddDTO.getUserId();
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formDataAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplainEntity.getExplains(), null);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            if (Objects.nonNull(explainMap.get(FieldTypeEnum.SERIALNO.getAlias())) && StringUtil.isEmpty(formDataAddDTO.getGroupNumber())) {
                workOrderDataFormDataService.getSerialNo(formDataAddDTO, corpid, explainMap.get(FieldTypeEnum.SERIALNO.getAlias()));
                JSONObject dataList = formDataAddDTO.getDataList();
                dataList.put(FieldTypeEnum.SERIALNO.getAlias(), formDataAddDTO.getSerialNo());
                paasFormDataEntity.setData(dataList);
            }

            ValidateDataDTO validateDataDTO = new ValidateDataDTO();
            BeanUtil.copyProperties(formDataAddDTO, validateDataDTO);
            JSONObject dataObj = formDataAddDTO.getDataList();

            //过滤data中null的数据
            String explainList1 = workOrderExplainEntity.getExplains();
            List<FieldAttrEntity> fieldList = JSONArray.parseArray(explainList1, FieldAttrEntity.class);
            //过滤data中数据为null的情况
            for (FieldAttrEntity fieldAttrEntity : fieldList) {
                String key = fieldAttrEntity.getAttr();
                Boolean isEmpty = (Objects.isNull(dataObj.get(key)));
                if (isEmpty) {
                    dataObj.remove(key);
                    continue;
                }
            }
            //初始化一个评价星级,统计要用,存在es
            dataObj.put(WorkOrderEnum.RATE_STAR.getAttr(), 0);
            formDataAddDTO.setDataList(dataObj);
            // 判断是否开启了流程
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            processFieldHelp.processSetVisible(paasFormEntityExt, explainMap);

            validateDataDTO.setData(formDataAddDTO.getDataList());
            validateDataDTO.setExplainMap(explainMap);
            //工单参数校验
            ProSaveHelp.analyticalData(validateDataDTO);
            //基本参数校验
            formDataValidateDataHelp.validateData(validateDataDTO);
            saasSaveHelp.beforeSave(validateDataDTO);
            // 修改是否完全出库
            Integer shipStatus = (Integer)validateDataDTO.getData().get(WorkOrderEnum.SHIP_STATUS.getAttr());
            if (WorkOrderShipStatusEnum.SHIPPED.getCode().equals(shipStatus)) {
                workOrderEntity.setAllOutbound(1);
            } else {
                workOrderEntity.setAllOutbound(0);
            }
            //赋默认值
//            saasSaveHelp.initDefaultValue(validateDataDTO);
            formDataAddDTO.setSaasNeedRedundantAttrPoJo(validateDataDTO.getSaasNeedRedundantAttrPoJo());

            BeanUtil.copyProperties(formDataAddDTO, workOrderEntity);
            String ownerId = formDataAddDTO.getUserId();
            workOrderEntity.setOwnerId(ownerId);
            if (Objects.nonNull(formDataAddDTO.getOwnerId()) && !formDataAddDTO.getOwnerId().isEmpty()) {
                workOrderEntity.setOwnerId(Objects.toString(formDataAddDTO.getOwnerId().get(0).getId(), ""));
            }
            workOrderEntity.setData(formDataAddDTO.getDataList());
            workOrderEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            workOrderEntity.setSerialNo(formDataAddDTO.getSerialNo());
            // 所属部门的id，由前端传入
            workOrderEntity.setDepartmentId(validateDataDTO.getDepartmentId());
            formDataAddDTO.setDepartmentId(validateDataDTO.getDepartmentId());
            //工单模板id, 由前端传入
//            workOrderEntity.setTemplateId(formDataAddDTO.getTemplateId());

            //根据form拿到templateId
            workOrderEntity.setTemplateId(workOrderFormEntityExt.getTemplateId());
            workOrderEntity.setMenuId(workOrderFormEntityExt.getMenuId());
            workOrderEntity.setCreatorId(userId);
            // 是否往form_data表中插入数据
            Integer noApprovalRequired = 1;
            if (workOrderFormEntityExt.getIsProcessForm().equals(1)) {
                StartProcessDTO startProcessDTO = new StartProcessDTO();
                BeanUtil.copyProperties(formDataAddDTO, startProcessDTO);
                startProcessDTO.setOwnerId(workOrderEntity.getOwnerId());
                startProcessDTO.setData(formDataAddDTO.getDataList());
                startProcessDTO.setCreatorId(userId);

                StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
                if (Objects.isNull(startProcessVO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
                }
                noApprovalRequired = startProcessVO.getNoApprovalRequired();
            }

            if (noApprovalRequired.equals(1)) {
                //不走工作流，保存
                workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());
                formDataAddDTO.setExplainMap(explainMap);
                Long dataId = proModelService.insertWorkOrder(formDataAddDTO, workOrderEntity);
                // TODO 工单暂时去掉业务规则
//                String businessRules = workOrderFormEntityExt.getBusinessRules();
//                if (!Objects.equals(1, formDataAddDTO.getIsBusinessRule()) && Objects.equals("1", businessRules)) {
//                    ActiveRuleDTO activeRuleDTO = new ActiveRuleDTO();
//                    BeanUtil.copyProperties(formDataAddDTO, activeRuleDTO);
//                    activeRuleDTO.setDataId(dataId);
//                    PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
//                    BeanUtil.copyProperties(workOrderEntity, paasFormDataEntity);
//                    activeRuleDTO.setPaasFormDataEntity(paasFormDataEntity);
//                    activeRuleDTO.setExplainList(fieldList);
//                    formDataActiveRuleHelp.activeRule(activeRuleDTO);
//                }
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else {
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            formDataAddVO.setFormDataId(workOrderEntity.getId());
            // 保存成功后删除草稿
            formDataDraftService.deleteAfterSave(formDataAddDTO);
        } catch (XbbException e) {
            LOG.warn("WorkOrderFormDataServiceImpl.add 出错", e);
            try {
                proEsHelper.physicalDeleteAllInAdd(workOrderEntity.getId(), corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            } catch (Exception ex) {
                LOG.warn("workorder add com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper.physicalDeleteAllInAdd() error", ex);
            }
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.add 出错", e);
            try {
                proEsHelper.physicalDeleteAllInAdd(workOrderEntity.getId(), corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            } catch (Exception ex) {
                LOG.warn("workorder add com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper.physicalDeleteAllInAdd() error", ex);
            }
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataAddVO addForOutLink(OuterLinkAddDTO outerLinkAddDTO) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        WorkOrderEntity workOrderEntity = new WorkOrderEntity();
        String corpid = outerLinkAddDTO.getCorpid();
        try {
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(outerLinkAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(outerLinkAddDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplainEntity.getExplains(), null);
            ValidateDataDTO validateDataDTO = new ValidateDataDTO();
            BeanUtil.copyProperties(outerLinkAddDTO, validateDataDTO);
            JSONObject dataObj = outerLinkAddDTO.getDataList();

            //过滤data中null的数据
            String explainList1 = workOrderExplainEntity.getExplains();
            List<FieldAttrEntity> fieldList = JSONArray.parseArray(explainList1, FieldAttrEntity.class);
            //过滤data中数据为null的情况
            for (FieldAttrEntity fieldAttrEntity : fieldList) {
                String key = fieldAttrEntity.getAttr();
                Boolean isEmpty = (Objects.isNull(dataObj.get(key)));
                if (isEmpty) {
                    dataObj.remove(key);
                    continue;
                }
            }
            //初始化一个评价星级,统计要用,存在es
            dataObj.put(WorkOrderEnum.RATE_STAR.getAttr(), 0);
            outerLinkAddDTO.setDataList(dataObj);
            // 判断是否开启了流程
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            processFieldHelp.processSetVisible(paasFormEntityExt, explainMap);

            validateDataDTO.setData(outerLinkAddDTO.getDataList());
            validateDataDTO.setExplainMap(explainMap);
            //工单参数校验
            ProSaveHelp.analyticalData(validateDataDTO);
            //基本参数校验
            formDataValidateDataHelp.validateData(validateDataDTO);
            validateDataDTO.setFromOuterLink(BasicConstant.ONE);
            saasSaveHelp.beforeSave(validateDataDTO);
            //赋默认值
//            saasSaveHelp.initDefaultValue(validateDataDTO);
            outerLinkAddDTO.setSaasNeedRedundantAttrPoJo(validateDataDTO.getSaasNeedRedundantAttrPoJo());

            BeanUtil.copyProperties(outerLinkAddDTO, workOrderEntity);
            // 这边不需要这个报价单组号，而且es插入会报错，所以去掉
            workOrderEntity.setGroupNumber(null);
            String ownerId = outerLinkAddDTO.getUserId();
            workOrderEntity.setOwnerId(ownerId);
            if (Objects.nonNull(outerLinkAddDTO.getOwnerId()) && !outerLinkAddDTO.getOwnerId().isEmpty()) {
                workOrderEntity.setOwnerId(Objects.toString(outerLinkAddDTO.getOwnerId().get(0).getId(), ""));
            }
            workOrderEntity.setData(outerLinkAddDTO.getDataList());
            workOrderEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            workOrderEntity.setSerialNo(outerLinkAddDTO.getSerialNo());
            // 所属部门的id，由前端传入
            workOrderEntity.setDepartmentId(validateDataDTO.getDepartmentId());
            outerLinkAddDTO.setDepartmentId(validateDataDTO.getDepartmentId());
            //工单模板id, 由前端传入
//            workOrderEntity.setTemplateId(formDataAddDTO.getTemplateId());

            //根据form拿到templateId
            workOrderEntity.setTemplateId(workOrderFormEntityExt.getTemplateId());
            workOrderEntity.setMenuId(workOrderFormEntityExt.getMenuId());
            workOrderEntity.setCreatorId(PaasConstant.OUT_LINK_USER_ID);
            // 是否往form_data表中插入数据
            Integer noApprovalRequired = 1;
//            if (workOrderFormEntityExt.getIsProcessForm().equals(1)) {
//                StartProcessDTO startProcessDTO = new StartProcessDTO();
//                BeanUtil.copyProperties(outerLinkAddDTO, startProcessDTO);
//                startProcessDTO.setOwnerId(workOrderEntity.getOwnerId());
//                startProcessDTO.setData(outerLinkAddDTO.getDataList());
//                startProcessDTO.setCreatorId(userId);
//
//                StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
//                if (Objects.isNull(startProcessVO)) {
//                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
//                }
//                noApprovalRequired = startProcessVO.getNoApprovalRequired();
//            }

            if (noApprovalRequired.equals(1)) {
                //不走工作流，保存
                workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());
                outerLinkAddDTO.setExplainMap(explainMap);
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(outerLinkAddDTO,formDataAddDTO);
                formDataAddDTO.setFromOuterLink(1);
                Long dataId = proModelService.insertWorkOrder(formDataAddDTO, workOrderEntity);
                // TODO 工单暂时去掉业务规则
//                String businessRules = workOrderFormEntityExt.getBusinessRules();
//                if (!Objects.equals(1, formDataAddDTO.getIsBusinessRule()) && Objects.equals("1", businessRules)) {
//                    ActiveRuleDTO activeRuleDTO = new ActiveRuleDTO();
//                    BeanUtil.copyProperties(formDataAddDTO, activeRuleDTO);
//                    activeRuleDTO.setDataId(dataId);
//                    PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
//                    BeanUtil.copyProperties(workOrderEntity, paasFormDataEntity);
//                    activeRuleDTO.setPaasFormDataEntity(paasFormDataEntity);
//                    activeRuleDTO.setExplainList(fieldList);
//                    formDataActiveRuleHelp.activeRule(activeRuleDTO);
//                }
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else {
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            formDataAddVO.setFormDataId(workOrderEntity.getId());
            // 保存成功后删除草稿
//            formDataDraftService.deleteAfterSave(formDataAddDTO);
        } catch (XbbException e) {
            LOG.warn("WorkOrderFormDataServiceImpl.add 出错", e);
            try {
                proEsHelper.physicalDeleteAllInAdd(workOrderEntity.getId(), corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            } catch (Exception ex) {
                LOG.warn("workorder add com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper.physicalDeleteAllInAdd() error", ex);
            }
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.add 出错", e);
            try {
                proEsHelper.physicalDeleteAllInAdd(workOrderEntity.getId(), corpid, IndexTypeEnum.IDX_SAAS_WORK_ORDER);
            } catch (Exception ex) {
                LOG.warn("workorder add com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper.physicalDeleteAllInAdd() error", ex);
            }
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddVO;
    }


    @Override
    public FormDataUpdateGetVO updateGet(FormDataUpdateGetDTO formDataUpdateGetDTO) throws XbbException {
        FormDataUpdateGetVO formDataUpdateGetVO = new FormDataUpdateGetVO();
        try {
            Integer saasMark = formDataUpdateGetDTO.getSaasMark();
            String corpid = formDataUpdateGetDTO.getCorpid();
            Long dataId = formDataUpdateGetDTO.getDataId();
            Integer businessType = formDataUpdateGetDTO.getBusinessType();
            WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, corpid);
            if (workOrderEntity == null || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(workOrderEntity.getFormId(), corpid);
            if (workOrderFormEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            SaasSpecialParamPojo saasSpecialParamPojo = formDataUpdateGetDTO.getSaasSpecialParamPojo();
            boolean fromCopy = Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE);
            if (!fromCopy) {
                // 是否可以编辑
                // 来自复制的不判断该逻辑
                // 是否可以编辑
                boolean isEdit = true;
                boolean isOpenWorkflow = commentHelp.isOpenWorkFlow(corpid);
                if (isOpenWorkflow) {
                    isEdit = workflowFormDataOperationService.isApprovedEdit(workOrderFormEntityExt.getId(), corpid, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), workOrderEntity.getFlowStatus(), formDataUpdateGetDTO.getLoginUser());
                } else {
                    isEdit = paasProcessTemplateModel.isApprovedEdit(formDataUpdateGetDTO.getAppId(), formDataUpdateGetDTO.getMenuId(), formDataUpdateGetDTO.getFormId(), formDataUpdateGetDTO.getLoginUser(), workOrderEntity);
                }
                if (!isEdit) {
                    throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200017);
                }
            }

            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            formDataUpdateGetVO.setPaasFormEntity(paasFormEntityExt);

            WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(workOrderEntity.getFormId(), corpid);
            if (workOrderExplainEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            // 获取字段解释信息，并且过滤不可见字段
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntityExt.getExplains(), FieldAttrEntity.class);

            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(formDataUpdateGetVO.getExplainList());
//            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
//            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
//            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, DepartmentEntity> departmentMap = commonHelp.getDepMap(userAndDepartmentGetDTO);

            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);

            // 获取协同人和负责人
            PaasFormDataEntityExt paasFormDataEntity = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(workOrderEntity, paasFormDataEntity);
            paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, saasMark, businessType, formDataUpdateGetDTO.getSubBusinessType(), paasFormDataEntity, userMap);
            List<String> coUserIds = handlerExplainDTO.getCoUserId();
            List<ReturnUserAndDepartmentPojo> coUserIdPojoList = new ArrayList<>();
            coUserIds.forEach(coUser -> {
                UserEntity userEntity = userMap.get(coUser);
                if (Objects.nonNull(userEntity)) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                    returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                    coUserIdPojoList.add(returnUserAndDepartmentPojo);
                }
            });
            if (Objects.isNull(handlerExplainDTO.getOwnerId()) || handlerExplainDTO.getOwnerId().isEmpty()){
                workOrderEntity.setOwnerId("");
            }else {
                workOrderEntity.setOwnerId(handlerExplainDTO.getOwnerId().get(0));
            }
            HandlerExplainVO handlerExplainVO;
            if (fromCopy) {
                handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            } else {
                handlerExplainVO = formDataUpdateGetExplainHandler.handleExplain(handlerExplainDTO);
            }
            if (handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }

            formDataUpdateGetVO.setExplainList(handlerExplainVO.getHeadList());


            // ---- 获取用户和部门容器end

            JSONObject data = workOrderEntity.getData();
            UserEntity ownerUserEntity = userMap.get(workOrderEntity.getOwnerId());
            ReturnUserAndDepartmentPojo returnUserAndDepartmentOwnerPojo = new ReturnUserAndDepartmentPojo();
            if (Objects.nonNull(ownerUserEntity)) {
                BeanUtil.copyProperties(ownerUserEntity, returnUserAndDepartmentOwnerPojo);
                returnUserAndDepartmentOwnerPojo.setId(ownerUserEntity.getUserId());
            }

            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(workOrderEntity, paasFormDataEntityExt);
            formDataUpdateGetVO.setData(paasFormDataEntityExt);

            //工单如果是自由流程，负责人字段显示并必填，指定流程不显示
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
            boolean isFree = Objects.equals(workOrderTemplateEntity.getIsFree(), 1);

            Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);

                if (!isFree) {
                    //指定流程。设置负责人不可见
                    if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.USER.getType())
                            && Objects.equals(WorkOrderEnum.MANAGER_ID.getAttr(), fieldAttrEntity.getAttr())) {
                        fieldAttrEntity.setVisible(0);
                    }
                } else {
                    if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.USER.getType()) && fieldAttrEntity.getAttr().equals(WorkOrderEnum.MANAGER_ID.getAttr()) && !fromCopy) {
                        fieldAttrEntity.setEditable(0);
                        WorkOrderFlowUserEntity workOrderFlowUserEntity = workOrderFlowUserService.getMainUser(dataId, corpid);
                        if (Objects.nonNull(workOrderFlowUserEntity)) {
                            formDataUpdateGetVO.getData().getData().put(fieldAttrEntity.getAttr(),workOrderFlowUserEntity.getUserId());
//                            UserEntity userEntity = userModel.getByKey(workOrderFlowUserEntity.getUserId(),corpid);
//                            if (Objects.nonNull(userEntity)) {
//                                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
//                                BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
//                                returnUserAndDepartmentPojo.setId(userEntity.getUserId());
//                                formDataUpdateGetVO.getData().getData().put(fieldAttrEntity.getAttr(), returnUserAndDepartmentPojo);
//                            }
                        }
                    }
                }
            }

            SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, saasAnalysisDataDTO);
            // saas特殊格式转换
            saasUpdateHelp.formatData(saasAnalysisDataDTO, workOrderEntity.getData());
            formatProductHelp.formatProduct(saasAnalysisDataDTO,workOrderEntity.getData(),null,false);
            /*
             * 工单模板选择，模拟解释的方式实现，不刷在解释里，编辑回显，我不想加的，凤娇一定要
             * start
             * */
            List<WorkOrderFormEntity> workOrderFormList = workOrderFormService.getTemplateWithPermission(formDataUpdateGetDTO.getLoginUser(), formDataUpdateGetDTO.getAppId(), null);
            FieldAttrEntity templateFieldAttrEntity = new FieldAttrEntity();
            if (workOrderFormList != null && workOrderFormList.size() == 1) {
                templateFieldAttrEntity.setVisible(0);
            } else {
                templateFieldAttrEntity.setVisible(1);
            }
            templateFieldAttrEntity.setAttrName(OperateModuleTypeEnum.WORK_ORDER.getName());
            templateFieldAttrEntity.setAttr(FieldTypeEnum.TEMPLATE.getAlias());
            templateFieldAttrEntity.setAttrType(FieldTypeEnum.TEMPLATE.getEsalias());
            templateFieldAttrEntity.setFieldType(FieldTypeEnum.TEMPLATE.getType());
            templateFieldAttrEntity.setEditable(0);
            templateFieldAttrEntity.setComboType(0);
            List<ItemPoJo> templateItem = new ArrayList<>();
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setValue(workOrderFormEntityExt.getId());
            itemPoJo.setText(workOrderFormEntityExt.getName());
            itemPoJo.setChecked(true);
            templateItem.add(itemPoJo);
            templateFieldAttrEntity.setItems(templateItem);
            formDataUpdateGetVO.getExplainList().add(0, templateFieldAttrEntity);

            data.put(FieldTypeEnum.TEMPLATE.getAlias(), workOrderFormEntityExt.getId());
            /*end*/



            // 编辑时saas字段显示特殊逻辑
            FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, formatExplainDTO);
            formatExplainDTO.setExplainList(explainList);
            formatExplainDTO.setDataEntity(paasFormDataEntityExt);

            formExplainHelp.formatExplain(formatExplainDTO, data);
            // saas特殊返回字段，放在一个对象中
            saasUpdateHelp.formatSaasAttrToReturn(formDataUpdateGetVO, formDataUpdateGetDTO.getBusinessType(), data);
            formDataUpdateGetVO.setSaasSpecialParamPojo(formatExplainDTO.getSaasSpecialParamPojo());

            data.put(FieldTypeEnum.OWNERID.getAlias(), Collections.singletonList(returnUserAndDepartmentOwnerPojo));
            data.put(FieldTypeEnum.COUSERID.getAlias(), coUserIdPojoList);
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), workOrderEntity.getDepartmentId());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), workOrderEntity.getSerialNo());
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), workOrderEntity.getDepartmentId());
            // 解析数据信息
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if (parseSingleRowDataVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            JSONObject result = parseSingleRowDataVO.getResult();
            // 获取关联数据的信息
            if (linkResultDataVO != null && !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty()) {
                linkResultDataVO.setData(result);
                linkResultDataVO.setExplainMap(explainMap);
                linkResultDataVO.setUserMap(userMap);
                linkResultDataVO.setDepartmentMap(departmentMap);
                linkResultDataVO.setExplainList(explainList);
                result = formDataLinkDataUpdateGetService.formDataLinkDataGet(formDataUpdateGetDTO, linkResultDataVO);
            }
            paasFormDataEntityExt.setData(result);
            formDataUpdateGetVO.setData(paasFormDataEntityExt);
            // TODO 需要增加返回权限

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.updateGet 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataUpdateGetVO;
    }

    /**
     * Description: 获取数据详情tab页面
     * @param workOrderDataDetailDTO
     * @return WorkOrderDataDetailVO
     * @throws XbbException
     * @author 刘阳
     * @date 2019/4/16 3:11 PM
     * @since v1.0
     */
    @Override
    public WorkOrderDataDetailVO getDetail(WorkOrderDataDetailDTO workOrderDataDetailDTO) throws XbbException {
        WorkOrderDataDetailVO workOrderDataDetailVO = new WorkOrderDataDetailVO();
        try {
            Long id = workOrderDataDetailDTO.getDataId();
            Integer businessType = workOrderDataDetailDTO.getBusinessType();
            String corpId = workOrderDataDetailDTO.getCorpid();
            WorkOrderEntity workOrderEntity = workOrderModel.getByKey(id, corpId);
            if (workOrderEntity == null || workOrderEntity.getDel() == 1 ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            Long templateId = workOrderEntity.getTemplateId();

            //获取模版名称
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(templateId, corpId);
            //针对corpid为空
            if (corpId == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002);
            }
            //获取负责人名称和阶段名
            List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.getNode(id,1, corpId);
            if (workOrderFlowNodeEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            //按钮枚举类初始化
            // TODO: 权限判断后期再加（一个编辑删除，一个是工作流的）
            //右上角编辑新建删除等权限
            List<ButtonPojo> buttonPojoList = new ArrayList<>();
            //工单流转操作权限按钮
            List<ButtonPojo> flowButtons = new ArrayList<>();
            List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessType(businessType);

            // 工单详情头部按钮
            WorkOrderCenterSecondTitlePojo workOrderCenterSecondTitlePojo = new WorkOrderCenterSecondTitlePojo();
            for (WorkOrderFlowNodeEntity entity : workOrderFlowNodeEntityList) {
                workOrderCenterSecondTitlePojo.setUserName(entity.getUserName());
                workOrderCenterSecondTitlePojo.setStageName(entity.getStageName());
                //TODO 移动端表头显示不同，这边需要补充

            }
            //head数据组装
            DetailTitlePojo detailTitlePojo = new DetailTitlePojo();
            detailTitlePojo.setName(workOrderTemplateEntity.getName() + OperateModuleTypeEnum.WORK.getName());
            WorkOrderCenterDataDetailPojo workOrderCenterDataDetailPojo = new WorkOrderCenterDataDetailPojo();
            workOrderCenterDataDetailPojo.setButton(buttonPojoList);
            workOrderCenterDataDetailPojo.setTitle(detailTitlePojo);
            workOrderCenterDataDetailPojo.setSecondTitle(workOrderCenterSecondTitlePojo);
            workOrderCenterDataDetailPojo.setOperation(flowButtons);
            workOrderDataDetailVO.setHead(workOrderCenterDataDetailPojo);

            //tab
            Long formId = workOrderEntity.getFormId();
            WorkOrderFormEntityExt workOrderFormEntity = workOrderFormModel.getByKey(formId, corpId);
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByKey(formId, corpId);
            Map<String, Object> param = BeanUtil.convertBean2Map(workOrderDataDetailDTO, true);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(workOrderDataDetailDTO, handlerExplainDTO, false);
            HandlerExplainVO handlerExplainVO = workOrderFormDataFormExplainHandleName.handlerExplain(explainList, workOrderFormEntity,param, handlerExplainDTO);
            if(handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            // 渲染业务规则
            List<DetailTabPojo> detailTabList;
            //获取子表单tab
            Map<Integer, List<UserTeamEntity>> userTeamMap = userTeamService.getUserTeam(id, workOrderDataDetailDTO.getCorpid(), businessType);
            List<String> ownerIds = new ArrayList<>();
            List<String> coUserIds = new ArrayList<>();
            for (Map.Entry<Integer, List<UserTeamEntity>> entry : userTeamMap.entrySet()) {
                if (Objects.equals(entry.getKey(), BasicConstant.MAIN_USER)) {
                    entry.getValue().forEach(team -> ownerIds.add(team.getUserId()));
                } else if (Objects.equals(entry.getKey(), BasicConstant.COOP_USER)) {
                    entry.getValue().forEach(team -> coUserIds.add(team.getUserId()));
                }
            }
            handlerExplainDTO.setOwnerId(ownerIds);
            handlerExplainDTO.setCoUserId(coUserIds);
            handlerExplainDTO.setCreatorId(workOrderEntity.getCreatorId());
            handlerExplainVO.setHandlerExplainDTO(handlerExplainDTO);
            detailTabList = ExplainUtil.getFieldListIncludeSubForm(handlerExplainVO, handlerExplainDTO);
            List<DetailTabPojo> detailTabPojoList = new ArrayList<>();
            //工单详情tab(枚举类)
            List<BusinessDetailTabEnum> tabEnumList = new ArrayList<>();
            if (PlatFormEnum.WEB.getValue().equals(workOrderDataDetailDTO.getPlatform())) {
                //web端tab
                tabEnumList = BusinessDetailTabEnum.getByBusinessType(businessType);
            } else if (PlatFormEnum.DINGTALK.getValue().equals(workOrderDataDetailDTO.getPlatform())) {
                //dingtalk端tab
                tabEnumList = BusinessDetailTabEnum.getByBusinessTypeForDingtalk(businessType);
            }
            for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                DetailTabPojo detailTabPojo = new DetailTabPojo();
                BeanUtil.copyProperties(tabEnum.getAnEnum(),detailTabPojo);
                detailTabPojo.setAttr(detailTabPojo.getKey());
                detailTabPojoList.add(detailTabPojo);
            }
            detailTabPojoList.addAll(detailTabList);
            workOrderDataDetailVO.setTab(detailTabPojoList);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderServiceImpl.getDetail()出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return workOrderDataDetailVO;
    }

    /**
     * Description: 获取工单内容
     *
     *
     * @param formDataGetDTO@throws XbbException
     * @author 刘阳
     * @date 2019/4/16 8:03 PM
     * @since v1.0
     */
    @Override
    public FormDataGetVO get(FormDataGetDTO formDataGetDTO) throws XbbException {
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        try {
            Long id = formDataGetDTO.getDataId();
            String corpid = formDataGetDTO.getCorpid();
            Integer saasMark = formDataGetDTO.getSaasMark();
            Integer businessType = formDataGetDTO.getBusinessType();
            WorkOrderEntity workOrderEntity = workOrderModel.getByKey(id, corpid);
            if (workOrderEntity == null || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            richTextService.addRichTextByDataId(workOrderEntity.getId(), corpid, formDataGetDTO.getFormId(),
                    Objects.equals(formDataGetDTO.getDistributorMark(), BasicConstant.ONE) ? XbbRefTypeEnum.transferBusinessType2Index(businessType) : businessType,
                    saasMark, workOrderEntity.getDel(), workOrderEntity.getData());
            //formList数据组装
            WorkOrderDataFormPojo workOrderDataFormPojo = new WorkOrderDataFormPojo();
            BeanUtil.copyProperties(workOrderEntity, workOrderDataFormPojo, true);

            Long formId = workOrderEntity.getFormId();
            WorkOrderFormEntityExt workOrderFormEntity = workOrderFormModel.getByKey(formId, corpid);
            if (workOrderFormEntity == null || workOrderFormEntity.getDel() == 1) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            if (workOrderExplainEntity == null || workOrderExplainEntity.getDel() == 1) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            String creatorId = workOrderEntity.getCreatorId();
            String ownerId = workOrderEntity.getOwnerId();
            Map<String, Object> param = BeanUtil.convertBean2Map(formDataGetDTO, true);
            //  获取字段解释信息，并且过滤不可见字段 start
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);

            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setCreatorId(creatorId);
            handlerExplainDTO.setExplainList(explainList);
            // 获取协同人和负责人
            PaasFormDataEntityExt paasFormDataEntity = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(workOrderEntity, paasFormDataEntity);
            JSONObject ownerAndCoUser = paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, saasMark, businessType, formDataGetDTO.getSubBusinessType(), paasFormDataEntity, userMap);

            HandlerExplainVO handlerExplainVO = workOrderFormDataFormExplainHandleName.handlerExplain(explainList, workOrderFormEntity,param, handlerExplainDTO);
            if(handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(headList.size());
            for (FieldAttrEntity fieldAttrEntity : headList) {
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
            }



            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(workOrderEntity, paasFormDataEntityExt);
            formDataGetVO.setFormList(paasFormDataEntityExt);

            JSONObject data = workOrderEntity.getData();
            data.put(FieldTypeEnum.ADDTIME.getAlias(), workOrderEntity.getAddTime());
            data.put(FieldTypeEnum.UPDATETIME.getAlias(), workOrderEntity.getUpdateTime());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), workOrderEntity.getSerialNo());
            data.put(FieldTypeEnum.CLOSETIME.getAlias(),workOrderEntity.getCloseTime());
            data.put(FieldTypeEnum.ENDTIME.getAlias(),workOrderEntity.getEndTime());
            data.put(FieldTypeEnum.CREATORID.getAlias(), creatorId);
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), workOrderEntity.getDepartmentId());
            // 设置创建者
            //setCreatorOrOwned(data, FieldTypeEnum.CREATORID.getAlias(), userMap.get(creatorId));

            // 设置协同人和负责人
            data.putAll(ownerAndCoUser);

            //  获取用户和部门容器 解析paas的特殊数据 end
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(formDataGetDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            // 解析数据
            ParseSingleRowDataVO parseSingleRowDataVO = formDataGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if(Objects.isNull(parseSingleRowDataVO)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            linkResultDataVO = linkResultDataVO == null ? new LinkResultDataVO() : linkResultDataVO;
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            data = parseSingleRowDataVO.getResult();
            if(!linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty()){
                linkResultDataVO.setData(data);
                linkResultDataVO.setExplainMap(explainMap);
                linkResultDataVO.setExplainList(headList);
                data = formDataLinkDataGetServiceImpl.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
            }
            /*// 负责人
            UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
            UserEntity managerEntity = new UserEntity();
            if(userTeamEnum == UserTeamEnum.UNKNOW) {
                managerEntity = userMap.get(ownerId);
            } else {
                Map<Long, String> userTeamMap = userTeamService.getMainUserMap(Collections.singletonList(id), paasFormDataEntityExt.getCorpid(), businessType, false);
                if(userTeamMap.containsKey(id)) {
                    String managerName = userTeamMap.get(id);
                    managerEntity.setName(managerName);
                }
            }
            setCreatorOrOwned(data, FieldTypeEnum.OWNERID.getAlias(), managerEntity);*/

            SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
            BeanUtil.copyProperties(formDataGetDTO, saasAnalysisDataDTO);
            // saas特殊格式转换
            saasGetHelp.formatData(saasAnalysisDataDTO, data);
            // saas特殊返回字段，放在一个对象中
//            saasGetHelp.formatSaasAttrToReturn(formDataGetVO, formDataGetDTO);
            // 解析saas pro的特殊数据，包括下拉框的回显
            PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> formDataEsEntities = new ArrayList<>();
            PaasFormDataEntityExt paasFormDataEsEntity = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(paasFormDataEntityExt, paasFormDataEsEntity);
            paasFormDataEsEntity.setData(data);
            formDataEsEntities.add(paasFormDataEsEntity);
            paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
            saasListHelp.analysisSaasDataList(paasFormDataEsListVO, explainMap);
            formDataEsEntities = paasFormDataEsListVO.getPaasFormDataESList();
            data = formDataEsEntities.get(0).getData();

            formDataGetVO.setData(data);
            //千分位
            formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, explainList, false);
            // 子表单和tab相关处理
            HandlerExplainVO tabHandlerExplainVO = new HandlerExplainVO();
            tabHandlerExplainVO.setHeadList(headList);
            tabHandlerExplainVO.setSaasMark(saasMark);
            tabHandlerExplainVO.setBusinessType(businessType);
            formDataGetVO.setHeadList(ExplainUtil.getFieldListNoIncludeSubForm(tabHandlerExplainVO).getHeadList());
            PaasFormEntity paasFormEntity = new PaasFormEntity();
            paasFormEntity.setFieldPosition(workOrderFormEntity.getFieldPosition());
            formDataGetVO.setPaasFormEntity(paasFormEntity);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("WorkOrderFormDataServiceImpl.get 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataGetVO;
    }

    /**
     * 回显创建者和负责人
     * @author 吴峰
     * @date 2019/3/28 16:56
     * @param data 数据
     * @param attr 创建者或者负责人的索引
     * @param userEntity 用户
     * @return void
     * @throws XbbException 业务异常
     */
    private void setCreatorOrOwned(JSONObject data, String attr, UserEntity userEntity) {
        if(Objects.isNull(userEntity)) {
            JSONObject jsonObject = new JSONObject();
            List<UserVO> userList = new ArrayList<>();
            jsonObject.put("value", "");
            jsonObject.put("list", userList);
            data.put(attr, jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            List<Object> userList = new ArrayList<>();
            JSONObject userVO = new JSONObject();
            userVO.put("id", userEntity.getUserId());
            userVO.put("name", userEntity.getName());
            userList.add(userVO);
            jsonObject.put("value", userEntity.getName());
            jsonObject.put("list", userList);
            data.put(attr, jsonObject);
        }
    }

    @Override
    public WorkOrderDataEsListVO listByEsForExport(FormDataListDTO formDataListDTO) throws XbbException{
        WorkOrderDataEsListVO formDataListVO;
        try {
            //分组条件
            Long formId = formDataListDTO.getFormId();
            String corpid = formDataListDTO.getCorpid();
            List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
            saasListHelp.packageGroupList(formDataListDTO,groupConditionsList,new ArrayList<>());
            formDataListDTO.getConditions().addAll(groupConditionsList);
            saasListHelp.addressSearchCondition(formDataListDTO);
            saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
            //过滤审批中数据
            filterApprovalData(formDataListDTO);
            WorkOrderFormEntityExt form = workOrderFormModel.getByKey(formId,corpid);
            if (form == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            if (workOrderExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String,FieldAttrEntity> explainMap = paasFormExplainService.getExpalinMap(explainList, XbbRefTypeEnum.WORK_ORDER.getCode(), corpid, formId);
            formDataListDTO.setExplainMap(explainMap);
            Map<String,String> sortMap = formDataListDTO.getSortMap();
            if (sortMap == null || sortMap.isEmpty()) {
                setListColumn(formDataListDTO);
            }
            formDataListVO = paasFormDataEsModel.workOrderList(formDataListDTO);
            formDataListVO.setForm(form);
            formDataListVO.setExplainMap(explainMap);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO, false);
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(form,paasFormEntityExt);
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
            HandlerExplainVO handlerExplainVO = formDataListFormExplainHandleName.handleExplain(handlerExplainDTO);
            if(handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            //首页不显示stage_id
            List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
            Iterator<FieldAttrEntity> iterator = headList.iterator();
            while (iterator.hasNext()){
                FieldAttrEntity entity = iterator.next();
                if (Objects.equals(entity.getAttr(), WorkOrderEnum.STAGE.getAttr())) {
                    iterator.remove();
                    break;
                }
            }
            formDataListVO.setHeadList(headList);
            formDataListVO.setPlatform(formDataListDTO.getPlatform());

            //处理工单特殊字段
            saasListHelp.handleEsWorkOrderData4Show(formDataListDTO, formDataListVO);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("workOrderFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }


    @Override
    public WorkOrderDataEsListVO list(FormDataListDTO formDataListDTO) throws XbbException{

        WorkOrderDataEsListVO workOrderDataEsListVO;
        Long formId = formDataListDTO.getFormId();
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(formDataListDTO.getLoginUser(),userEntity);
            // app端范围筛选
            saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(), userEntity, XbbRefTypeEnum.WORK_ORDER.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        } else {
            rangeScreen(formDataListDTO);
        }
        //是否是全部工单列表
        if (Objects.equals(formId, 0L)) {
            //全部列表
            return allList(formDataListDTO);
        }
        List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
        saasListHelp.packageGroupList(formDataListDTO,groupConditionsList,new ArrayList<>());
        saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
        formDataListDTO.getConditions().addAll(groupConditionsList);
        saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
        saasListHelp.addressSearchCondition(formDataListDTO);
        saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
        //过滤审批中数据
        filterApprovalData(formDataListDTO);
        WorkOrderFormEntityExt form = workOrderFormModel.getByKey(formId,corpid);
        if (form == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
        if (workOrderExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
        // 处理一下对应的标签
        Boolean hasLabel = false;
        for (FieldAttrEntity attrEntity : explainList) {
            if (Objects.equals(attrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                hasLabel = true;
            }
        }
        Map<String,FieldAttrEntity> explainMap = paasFormExplainService.getExpalinMap(explainList, XbbRefTypeEnum.WORK_ORDER.getCode(), corpid, formId);
        formDataListDTO.setExplainMap(explainMap);

        // 开启电话掩码后不允许进行电话字段的查询
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(conditions)) {
            for (ConditionsEntityExt condition : conditions) {
                FieldAttrEntity fieldAttr = explainMap.get(condition.getAttr());
                if (Objects.nonNull(fieldAttr) && ExplainUtil.isOpenTelephoneMask(fieldAttr, formDataListDTO.getLoginUser())) {
                    throw new XbbException(ErrorCodeEnum.API_ERROR_352000);
                }
            }
        }

        Map<String,String> sortMap = formDataListDTO.getSortMap();
        if (sortMap == null || sortMap.isEmpty()) {
            setListColumn(formDataListDTO);
        }
        workOrderDataEsListVO = paasFormDataEsModel.workOrderList(formDataListDTO);
        workOrderDataEsListVO.setForm(form);
        workOrderDataEsListVO.setExplainMap(explainMap);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO, false);
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        BeanUtil.copyProperties(form,paasFormEntityExt);
        paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
        paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        handlerExplainDTO.setExplainList(explainList);
        handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
        HandlerExplainVO handlerExplainVO = formDataListFormExplainHandleName.handleExplain(handlerExplainDTO);
        if(handlerExplainVO == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        //首页不显示stage_id
        List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
        Iterator<FieldAttrEntity> iterator = headList.iterator();
        Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
        while (iterator.hasNext()){
            FieldAttrEntity entity = iterator.next();
            if (Objects.equals(entity.getAttr(), WorkOrderEnum.STAGE.getAttr())) {
                iterator.remove();
            }else if (Objects.equals(entity.getAttr(), WorkOrderEnum.SPARE_PARTS.getAttr()) && !isJxcUse) {
                //            不可开启进销存的情况下过滤子表单字段
                SubFormPoJo subForm = entity.getSubForm();
                List<FieldAttrEntity> fieldAttrEntities = (List<FieldAttrEntity>)subForm.getItems();
                fieldAttrEntities.removeIf(entity1 -> Objects.equals(entity1.getAttr(), SelectProductEnum.OUTSTOCK_NUM.getAttr()) || Objects.equals(entity1.getAttr(), SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr()));
                subForm.setItems(fieldAttrEntities);
            }
        }
        // 【审批中】分组数据禁用快速编辑
        if (Objects.equals(formDataListDTO.getDefaultGroup(), 1) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
            headList.forEach(item -> item.setEditable(0));
        }
        workOrderDataEsListVO.setHeadList(headList);
        workOrderDataEsListVO.setPlatform(formDataListDTO.getPlatform());
        if(PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform())) {
            saasListHelp.setOption(workOrderDataEsListVO,formDataListDTO);
            saasListHelp.handleEsData4Show(formDataListDTO,workOrderDataEsListVO);
//            saasListHelp.setMainUser(formDataListVO,corpid,XbbRefTypeEnum.WORK_ORDER,false);
            saasListHelp.analysisSaasDataList4Web(workOrderDataEsListVO,explainMap);
            // 单模板解释
            proFormHelp.setProductAccuracy(explainMap.getOrDefault(WorkOrderEnum.SPARE_PARTS.getAttr(),new FieldAttrEntity()),corpid,userId);
            Map<String,Object> thousandExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            FieldAttrEntity fieldAttrEntity = explainMap.get(WorkOrderEnum.SPARE_PARTS.getAttr());
            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
            if (subForm != null && subForm.getItems() != null) {
                List<? extends FieldAttrEntity> fieldAttrEntityList = subForm.getItems();
                for (FieldAttrEntity entity : fieldAttrEntityList) {
                    if (SelectProductEnum.ThousandBitsAttr(entity.getAttr())){
                        thousandExplainMap.put(entity.getAttr(),entity);
                    }
                }
            }
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            for(WorkOrderEntityExt workOrderEntityExt : workOrderDataEsListVO.getPaasFormDataESList()){
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(workOrderEntityExt,paasFormDataEntityExt);
                paasFormDataEntityExtList.add(paasFormDataEntityExt);
            }
            BeanUtil.copyProperties(workOrderDataEsListVO,formDataListVO);
            formDataListVO.setPaasFormDataESList(paasFormDataEntityExtList);
            formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
            formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, false);
            // 下面开始实施备件的解析精度千分位
            for (PaasFormDataEntityExt paasFormDataEntity : formDataListVO.getPaasFormDataESList()) {
                JSONArray resultArray = paasFormDataEntity.getData().getJSONArray(WorkOrderEnum.SPARE_PARTS.getAttr());
                JSONObject resultObject = new JSONObject();
                if (Objects.nonNull(resultArray) && resultArray.size() > 0){
                    resultObject = resultArray.getJSONObject(0);
                }
                //千分位解析
                for (String attr : resultObject.keySet()) {
                    // 详情tab是否启用金额
                    if (SelectProductEnum.ThousandBitsAttr(attr) && Objects.nonNull(thousandExplainMap.get(attr))){
                        if (Objects.equals(((FieldAttrEntity)thousandExplainMap.get(attr)).getAmountFlag(),1)){
                            formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(resultObject, attr, thousandExplainMap, false);
                        }
                    }
                }
            }
            List<WorkOrderEntityExt> workOrderEntityExtList = new ArrayList<>();
            try {
                BeanUtil.copyPropertiesList(formDataListVO.getPaasFormDataESList(),workOrderEntityExtList,WorkOrderEntityExt.class);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            // 处理列表页字段排序
            explainFieldSort(formDataListDTO, formDataListVO);
            //处理冻结字段和隐藏字段（在排序后设置）
            setFixedAndInvisible(formDataListDTO, formDataListVO);
            workOrderDataEsListVO.setHeadList(formDataListVO.getHeadList());
            workOrderDataEsListVO.setPaasFormDataESList(workOrderEntityExtList);
        }else if(PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())){
            saasListHelp.analysisSaasDataList(workOrderDataEsListVO,explainMap);
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            Map<Long, WorkOrderEntityExt> workOrderMap = new HashMap<>(PageConstant.DEFAULT_PAGE_SIZE);
            for(WorkOrderEntityExt workOrderEntityExt : workOrderDataEsListVO.getPaasFormDataESList()){
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(workOrderEntityExt,paasFormDataEntityExt);
                paasFormDataEntityExtList.add(paasFormDataEntityExt);
                workOrderMap.put(workOrderEntityExt.getId(), workOrderEntityExt);
            }
            BeanUtil.copyProperties(workOrderDataEsListVO,formDataListVO);
            formDataListVO.setForm(paasFormEntityExt);
            paasFormEntityExt.setSummaryList(form.getSummary());
            paasFormEntityExt.setLabelsList(form.getLabels());
            paasFormEntityExt.setCustomTitle(form.getCustomTitle());
            formDataListVO.setPaasFormDataESList(paasFormDataEntityExtList);
            formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
            formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, false);
            // 摘要和标题的封装
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, null, null);
            List<WorkOrderEntityExt> workOrderEntityExtList = new ArrayList<>();
            try {
                BeanUtil.copyPropertiesList(formDataListVO.getPaasFormDataESList(),workOrderEntityExtList,WorkOrderEntityExt.class);
                // 后续渲染列表页回显数据时需要用到这些参数
                workOrderEntityExtList.forEach(item -> {
                    WorkOrderEntityExt entityExt = workOrderMap.get(item.getId());
                    item.setStartTime(entityExt.getStartTime());
                    item.setActualTime(entityExt.getActualTime());
                    item.setStatus(entityExt.getStatus());
                    item.setCloseTime(entityExt.getCloseTime());
                    item.setEndTime(entityExt.getEndTime());
                    item.setExpectedTime(entityExt.getExpectedTime());
                    item.setTemplateId(entityExt.getTemplateId());
                    item.setNowStageId(entityExt.getNowStageId());
                });
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            workOrderDataEsListVO.setPaasFormDataESList(workOrderEntityExtList);
        }
        /* ==================== 上部按钮权限和下部按钮权限 ==================== */
        List<ButtonPojo> topPermissionList = new ArrayList<>();
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.WORK_ORDER_ROB.getCode())) {
            for (ListTopButtonEnum topButtonEnum : ListTopButtonEnum.getByBusinessType(formDataListDTO.getSubBusinessType())) {
                String permission = topButtonEnum.getProPermissionAlias();
                // permission为1的按钮一直存在的或还没加权限alias
                if (!permSet.contains(permission) && !Objects.equals(permission, StringConstant.POSITIVE_NUMBER)) {
                    continue;
                }
                ButtonPojo buttonPojo = new ButtonPojo();
                BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
                if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.WAIT_ROB.getAttr())) {
                    ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                    buttonExtraPojo.setAppId(paasFormEntityExt.getAppId());
                    buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WORK_ORDER_ROB.getCode());
                    buttonPojo.setButtonExtra(buttonExtraPojo);
                    buttonExtraPojo.setHasNumber(true);
//                    buttonPojo.setValue(buttonPojo.getValue() + "(" + saasListHelp.getWaitRob(formDataListDTO.getLoginUser()) + ")");
                }
                if (Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))
                        && (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.IMPORT.getAttr()))) {
                    continue;
                }
                if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.EXPORT.getAttr())) {
                    List<ButtonPojo> subButtonList = new ArrayList<ButtonPojo>(){{
                        add(new ButtonPojo(){{BeanUtil.copyProperties(topButtonEnum.getAnEnum(), this);}});
                    }};
                    List<SaasSubButtonEnum> saasSubButtonEnumList = SaasSubButtonEnum.getByPermissionAlias(formDataListDTO.getSubBusinessType(),topButtonEnum,formDataListDTO.getLoginUser().getPermSet());
                    saasSubButtonEnumList.forEach(item->{
                        subButtonList.add(new ButtonPojo(){{setAttr(item.getAlias());setValue(item.getName());}});
                    });
                    buttonPojo.setSubButtons(subButtonList);
                }
                topPermissionList.add(buttonPojo);
            }
        }
        workOrderDataEsListVO.setTopPermissions(topPermissionList);
        List<ListBatchEnum> listBatchEnumList = ListBatchEnum.getByBusinessType(formDataListDTO.getSubBusinessType());
        List<ButtonPojo> batchButtonList = new ArrayList<>();
        List<SaasBatchEnum> saasBatchEnums = Arrays.asList(SaasBatchEnum.ADD_LABEL, SaasBatchEnum.REMOVE_LABEL);
        for (ListBatchEnum batchEnum : listBatchEnumList) {
            // permission为1的按钮一直存在的
            String permissionAlias = batchEnum.getProPermissionAlias();
            if (!permSet.contains(permissionAlias) && !Objects.equals(permissionAlias, StringConstant.POSITIVE_NUMBER)) {
                continue;
            }
            if (!hasLabel && saasBatchEnums.contains(batchEnum.getAnEnum()) ){
                continue;
            }
            // 审批中分组只保留打印操作
            if (Objects.equals(formDataListDTO.getDefaultGroup(), 1) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
                if (!Objects.equals(batchEnum, ListBatchEnum.WORK_ORDER_PRINT)) {
                    continue;
                }
            }
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(batchEnum.getAnEnum(), buttonPojo);
            batchButtonList.add(buttonPojo);
        }
        CustomButtonListDTO customButtonListDTO = new CustomButtonListDTO();
        customButtonListDTO.setBusinessType(formDataListDTO.getBusinessType());
        customButtonListDTO.setFormId(formDataListDTO.getFormId());
        customButtonListDTO.setSaasMark(formDataListDTO.getSaasMark());
        customButtonListDTO.setCorpid(formDataListDTO.getCorpid());
        customButtonListDTO.setLoginUser(formDataListDTO.getLoginUser());
        customButtonListDTO.setType(ButtonTypeEnum.LIST.getCode());
        CustomButtonListVO formCustomButtonListVO = customButtonService.listByPermission(customButtonListDTO);
        if (Objects.nonNull(formCustomButtonListVO) && CollectionsUtil.isNotEmpty(formCustomButtonListVO.getCustomButtonList())) {
            formCustomButtonListVO.getCustomButtonList().forEach(item->{
                ButtonPojo buttonPojo = new ButtonPojo();
                buttonPojo.setActionList(item.getActionList());
                buttonPojo.setValue(item.getName());
                buttonPojo.setAttr(PaasConstant.LOW_CODE);
                batchButtonList.add(buttonPojo);
            });
        }
        workOrderDataEsListVO.setBottomPermissions(batchButtonList);
//        setButtons(formDataListDTO, workOrderDataEsListVO);
        return workOrderDataEsListVO;
    }
    /**
     * Description: 工单全部列表
     * @param formDataListDTO
     * @return com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO
     * @author 魏荣杰
     * @date 2019/8/27 14:05
     * @since v4.3.0
     */
    private WorkOrderDataEsListVO allList(FormDataListDTO formDataListDTO) throws XbbException {
        WorkOrderDataEsListVO workOrderDataEsListVO;
        Long formId = formDataListDTO.getFormId();
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
        saasListHelp.packageGroupList(formDataListDTO,groupConditionsList,new ArrayList<>());
        saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
        formDataListDTO.getConditions().addAll(groupConditionsList);
        saasListHelp.addressSearchCondition(formDataListDTO);
        saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
        //过滤审批中数据
        filterApprovalData(formDataListDTO);
        WorkOrderFormEntityExt form = workOrderFormModel.getDefaultAllListForm();
        if (form == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        //表头用解释，使用基本模板解释
        WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getDefaultAllListExplain(corpid);
        if (workOrderExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String,FieldAttrEntity> explainMap = paasFormExplainService.getExpalinMap(explainList, XbbRefTypeEnum.WORK_ORDER.getCode(), corpid, formId);
        formDataListDTO.setExplainMap(explainMap);
        Map<String,String> sortMap = formDataListDTO.getSortMap();
        if (sortMap == null || sortMap.isEmpty()) {
            setListColumn(formDataListDTO);
        }

        // 开启电话掩码后不允许进行电话字段的查询
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(conditions)) {
            // 全部工单列表特殊处理
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", formDataListDTO.getCorpid());
            param.put("del", 0);
            param.put("enable", 1);
            List<WorkOrderFormEntity> formList = workOrderFormModel.findEntitys(param);
            List<WorkOrderExplainEntity> allExplainList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(formList)) {
                List<Long> formIdIn = formList.stream().map(WorkOrderFormEntity::getId).collect(Collectors.toList());
                param.clear();
                param.put("corpid", formDataListDTO.getCorpid());
                param.put("del", 0);
                param.put("formIdIn", formIdIn);
                allExplainList = workOrderExplainModel.findEntitys(param);
            }
            for (ConditionsEntityExt condition : conditions) {
                for (WorkOrderExplainEntity explain : allExplainList) {
                    Map<String, FieldAttrEntity> currentExplainMap = ExplainUtil.getExplainMap(explain.getExplains());
                    FieldAttrEntity phoneField = currentExplainMap.get(condition.getAttr());
                    boolean isOpenTelephoneMask = ExplainUtil.isOpenTelephoneMask(phoneField, formDataListDTO.getLoginUser());
                    if (isOpenTelephoneMask) {
                        throw new XbbException(ErrorCodeEnum.API_ERROR_352000);
                    }
                }
            }
        }

        //获取当前操作人有权限的工单模板
        List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormService.getTemplateWithPermission(formDataListDTO.getLoginUser(), formDataListDTO.getAppId(), null);
        List<Long> formIds = new ArrayList<>();
        for (WorkOrderFormEntity entity : workOrderFormEntityList) {
            formIds.add(entity.getId());
        }
        formDataListDTO.setFormId(null);
        formDataListDTO.setFormIdList(formIds);
        workOrderDataEsListVO = paasFormDataEsModel.workOrderList(formDataListDTO);
        workOrderDataEsListVO.setForm(form);
        workOrderDataEsListVO.setExplainMap(explainMap);


        //默认全部模板的解释处理
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO, false);
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        BeanUtil.copyProperties(form,paasFormEntityExt);
        paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
        paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        handlerExplainDTO.setExplainList(explainList);
        handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
        HandlerExplainVO handlerExplainVO = formDataListFormExplainHandleName.handleExplain(handlerExplainDTO);
        if(handlerExplainVO == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        //首页不显示stage_id
        List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
        Iterator<FieldAttrEntity> iterator = headList.iterator();
        while (iterator.hasNext()){
            FieldAttrEntity entity = iterator.next();
            if (Objects.equals(entity.getAttr(), WorkOrderEnum.STAGE.getAttr())) {
                iterator.remove();
                break;
            }
        }
        // 【审批中】分组数据禁用快速编辑
        if (Objects.equals(formDataListDTO.getDefaultGroup(), 1) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
            headList.forEach(item -> item.setEditable(0));
        }
        workOrderDataEsListVO.setHeadList(headList);
        workOrderDataEsListVO.setPlatform(formDataListDTO.getPlatform());

        //查询出来的工单数据各模板解释处理
        List<WorkOrderFormEntityExt> workOrderFormEntityExtList = workOrderFormModel.getByIdIn(formIds, corpid);
        Map<Long, WorkOrderFormEntityExt> workOrderFormEntityExtMap = new HashMap<>();
        List<Long> allFormIds = new ArrayList<>();
        Map<Long, PaasFormEntityExt> formMap = new HashMap<>();
        for (WorkOrderFormEntityExt entityExt : workOrderFormEntityExtList) {
            workOrderFormEntityExtMap.put(entityExt.getId(), entityExt);
            PaasFormEntityExt paasForm = new PaasFormEntityExt();
            BeanUtil.copyProperties(entityExt, paasForm);
            allFormIds.add(entityExt.getId());
            formMap.put(paasForm.getId(), paasForm);
        }
        Map<Long, String> id2LabelAttr = new HashMap<>(formIds.size());
        List<WorkOrderExplainEntity> workOrderExplainEntityList = workOrderExplainModel.getByFormIdIn(formIds, corpid);
        Map<Long, Map<String,FieldAttrEntity>> formIdAndExplainMap = new HashMap<>();
        Map<Long, List<FieldAttrEntity>> formIdAndHeadListMap = new HashMap<>();
        Map<String,Object> thousandExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (WorkOrderExplainEntity explainEntity : workOrderExplainEntityList) {
            // 获取对应表单的解释
            List<FieldAttrEntity> explains = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity item : explains) {
                if (Objects.equals(item.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    id2LabelAttr.put(explainEntity.getFormId(), item.getAttr());
                    break;
                }
            }
            Map<String,FieldAttrEntity> explainsMap = paasFormExplainService.getExpalinMap(explains, XbbRefTypeEnum.WORK_ORDER.getCode(), corpid, explainEntity.getFormId());
            formIdAndExplainMap.put(explainEntity.getFormId(), explainsMap);
            // 单模板解释
            proFormHelp.setProductAccuracy(explainMap.getOrDefault(WorkOrderEnum.SPARE_PARTS.getAttr(),new FieldAttrEntity()),corpid,userId);
            FieldAttrEntity fieldAttrEntity = explainMap.get(WorkOrderEnum.SPARE_PARTS.getAttr());
            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
            if (subForm != null && subForm.getItems() != null) {
                List<? extends FieldAttrEntity> fieldAttrEntityList = subForm.getItems();
                for (FieldAttrEntity entity : fieldAttrEntityList) {
                    if (SelectProductEnum.ThousandBitsAttr(entity.getAttr())){
                        thousandExplainMap.put(entity.getAttr(),entity);
                    }
                }
            }
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormEntityExtMap.get(explainEntity.getFormId());

            HandlerExplainDTO handlerExplainDTO1 = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO1, false);
            PaasFormEntityExt paasFormEntity = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntity);
            paasFormEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
            paasFormEntity.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            handlerExplainDTO1.setExplainList(explains);
            handlerExplainDTO1.setPaasFormEntityExt(paasFormEntity);
            handlerExplainDTO1.setIsFilter(false);
            HandlerExplainVO handlerExplainVO1 = formDataListFormExplainHandleName.handleExplain(handlerExplainDTO1);
            if(handlerExplainVO1 != null) {
                formIdAndHeadListMap.put(explainEntity.getFormId(), handlerExplainVO1.getHeadList());
            }

        }

        if (PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform())) {
            saasListHelp.setOption(workOrderDataEsListVO,formDataListDTO);
            saasListHelp.handleEsData4Show(formDataListDTO,workOrderDataEsListVO);
            saasListHelp.analysisSaasDataAllList4Web(workOrderDataEsListVO,formIdAndExplainMap);
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            for(WorkOrderEntityExt workOrderEntityExt : workOrderDataEsListVO.getPaasFormDataESList()){
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(workOrderEntityExt, paasFormDataEntityExt);
                paasFormDataEntityExtList.add(paasFormDataEntityExt);
            }

            BeanUtil.copyProperties(workOrderDataEsListVO,formDataListVO);
            formDataListVO.setPaasFormDataESList(paasFormDataEntityExtList);
            formDataAllListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO, formIdAndHeadListMap);
            formDataAllListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, false, formIdAndHeadListMap);
            // 下面开始实施备件的解析精度千分位
            for (PaasFormDataEntityExt paasFormDataEntity : formDataListVO.getPaasFormDataESList()) {
                JSONArray resultArray = paasFormDataEntity.getData().getJSONArray(WorkOrderEnum.SPARE_PARTS.getAttr());
                JSONObject resultObject = new JSONObject();
                if (Objects.nonNull(resultArray) && resultArray.size() > 0){
                    resultObject = resultArray.getJSONObject(0);
                }
                //千分位解析
                for (String attr : resultObject.keySet()) {
                    // 详情tab是否启用金额
                    if (SelectProductEnum.ThousandBitsAttr(attr) && Objects.nonNull(thousandExplainMap.get(attr))){
                        if (Objects.equals(((FieldAttrEntity)thousandExplainMap.get(attr)).getAmountFlag(),1)){
                            formDataAnalysisHelp.analysisAmountOfThousandBitsNomal(resultObject, attr, thousandExplainMap, false);
                        }
                    }
                }
            }
            Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
            if (!isJxcUse) {
                List<FieldAttrEntity> headList1 = formDataListVO.getHeadList();
                Iterator<FieldAttrEntity> headIterator = headList1.iterator();
                while (headIterator.hasNext()){
                    FieldAttrEntity entity = headIterator.next();
                    if (Objects.equals(entity.getAttr(), WorkOrderEnum.SPARE_PARTS.getAttr())) {
                        SubFormPoJo subForm = entity.getSubForm();
                        List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                        Iterator<FieldAttrEntity> iterator1 = fieldAttrEntityList.iterator();
                        while (iterator1.hasNext()) {
                            FieldAttrEntity entity1 = iterator1.next();
                            if (Objects.equals(entity1.getAttr(), SelectProductEnum.OUTSTOCK_NUM.getAttr()) || Objects.equals(entity1.getAttr(), SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())) {
                                iterator1.remove();
                            }
                        }
                        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntityList));
                        subForm.setItems(fieldAttrEntityList);
                        break;
                    }
                }
            }
            List<WorkOrderEntityExt> workOrderEntityExtList = new ArrayList<>();
            try {
                BeanUtil.copyPropertiesList(formDataListVO.getPaasFormDataESList(),workOrderEntityExtList,WorkOrderEntityExt.class);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
//            workOrderDataEsListVO.setHeadList(formDataListVO.getHeadList());
            explainFieldSort(formDataListDTO, formDataListVO);
            //列表隐藏和列表冻结(在排序后设置)
            setFixedAndInvisible(formDataListDTO, formDataListVO);
            workOrderDataEsListVO.setPaasFormDataESList(workOrderEntityExtList);
        } else if (PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())) {
            saasListHelp.analysisSaasDataList(workOrderDataEsListVO,explainMap);
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            Map<Long, WorkOrderEntityExt> workOrderMap = new HashMap<>(PageConstant.DEFAULT_PAGE_SIZE);
            for(WorkOrderEntityExt workOrderEntityExt : workOrderDataEsListVO.getPaasFormDataESList()){
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(workOrderEntityExt,paasFormDataEntityExt);
                paasFormDataEntityExtList.add(paasFormDataEntityExt);
                workOrderMap.put(workOrderEntityExt.getId(), workOrderEntityExt);
            }
            BeanUtil.copyProperties(workOrderDataEsListVO,formDataListVO);
            formDataListVO.setForm(paasFormEntityExt);
            paasFormEntityExt.setSummaryList(form.getSummary());
            paasFormEntityExt.setLabelsList(form.getLabels());
            paasFormEntityExt.setCustomTitle(form.getCustomTitle());
            formDataListVO.setPaasFormDataESList(paasFormDataEntityExtList);
            formDataAllListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO, formIdAndHeadListMap);
            formDataAllListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, false, formIdAndHeadListMap);
            // 摘要和标题的封装
            Map<Long, LabelPojo> allLabelList = labelHelp.getAllLabelList(formDataListDTO.getAppId(), allFormIds, XbbRefTypeEnum.WORK_ORDER.getCode(), formDataListDTO.getCorpid());
            formDataListVO.getPaasFormDataESList().forEach(item->{
                Long formId1 = item.getFormId();
                String s = id2LabelAttr.get(formId1);
                if (StringUtil.isNotEmpty(s)) {
                    JSONArray jsonArray = item.getData().getJSONArray(s);
                    if (CollectionsUtil.isNotEmpty(jsonArray)) {
                        JSONArray jsonArray1 = new JSONArray();
                        jsonArray.forEach(item1->{
                            jsonArray1.add(allLabelList.get(Long.parseLong(item1.toString())));
                        });
                        item.getData().put(s,jsonArray1);
                    }
                }
            });
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, formMap, formIdAndHeadListMap);
            List<WorkOrderEntityExt> workOrderEntityExtList = new ArrayList<>();
            try {
                BeanUtil.copyPropertiesList(formDataListVO.getPaasFormDataESList(),workOrderEntityExtList,WorkOrderEntityExt.class);
                // 后续渲染列表页回显数据时需要用到这些参数
                workOrderEntityExtList.forEach(item -> {
                    WorkOrderEntityExt entityExt = workOrderMap.get(item.getId());
                    item.setStartTime(entityExt.getStartTime());
                    item.setActualTime(entityExt.getActualTime());
                    item.setStatus(entityExt.getStatus());
                    item.setCloseTime(entityExt.getCloseTime());
                    item.setEndTime(entityExt.getEndTime());
                    item.setExpectedTime(entityExt.getExpectedTime());
                    item.setTemplateId(entityExt.getTemplateId());
                    item.setNowStageId(entityExt.getNowStageId());
                });
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
            workOrderDataEsListVO.setPaasFormDataESList(workOrderEntityExtList);
        }

        /* ==================== 上部按钮权限和下部按钮权限 ==================== */
        List<ButtonPojo> topPermissionList = new ArrayList<>();
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (!Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.WORK_ORDER_ROB.getCode())) {
            for (ListTopButtonEnum topButtonEnum : ListTopButtonEnum.getByBusinessType(formDataListDTO.getSubBusinessType())) {
                if (Objects.equals(topButtonEnum, ListTopButtonEnum.WROK_ORDER_EXPORT)) {
                    continue;
                }
                String permission = topButtonEnum.getProPermissionAlias();
                // permission为1的按钮一直存在的或还没加权限alias
                if (!permSet.contains(permission) && !Objects.equals(permission, StringConstant.POSITIVE_NUMBER)) {
                    continue;
                }
                ButtonPojo buttonPojo = new ButtonPojo();
                BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
                if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.WAIT_ROB.getAttr())) {
                    PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.WORK_ORDER.getAlias(), corpid);
                    ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                    buttonExtraPojo.setAppId(paasAppEntity.getId());
                    buttonExtraPojo.setSubBusinessType(XbbRefTypeEnum.WORK_ORDER_ROB.getCode());
                    buttonPojo.setButtonExtra(buttonExtraPojo);
                    buttonExtraPojo.setHasNumber(true);
                }
                topPermissionList.add(buttonPojo);
            }
        }
        workOrderDataEsListVO.setTopPermissions(topPermissionList);
        List<ListBatchEnum> listBatchEnumList = ListBatchEnum.getByBusinessType(formDataListDTO.getSubBusinessType());
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_BATCH_EDIT);
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_ADD_LABEL);
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_REMOVE_LABEL);
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_PRINT);
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_ADD_COUSER);
        listBatchEnumList.remove(ListBatchEnum.WORK_ORDER_DEL_COUSER);
        List<ButtonPojo> batchButtonList = new ArrayList<>();
        for (ListBatchEnum batchEnum : listBatchEnumList) {
            // permission为1的按钮一直存在的
            String permissionAlias = batchEnum.getProPermissionAlias();
            if (!permSet.contains(permissionAlias) && !Objects.equals(permissionAlias, StringConstant.POSITIVE_NUMBER)) {
                continue;
            }
            // 审批中分组只保留打印操作
            if (Objects.equals(formDataListDTO.getDefaultGroup(), 1) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
                if (!Objects.equals(batchEnum, ListBatchEnum.WORK_ORDER_PRINT)) {
                    continue;
                }
            }
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(batchEnum.getAnEnum(), buttonPojo);
            batchButtonList.add(buttonPojo);
        }
        workOrderDataEsListVO.setBottomPermissions(batchButtonList);
        return workOrderDataEsListVO;
    }

    private void filterApprovalData(FormDataListDTO formDataListDTO) {
        if (Objects.equals(formDataListDTO.getDefaultGroup(), 1) && Objects.equals(formDataListDTO.getListGroupId(), Long.valueOf(ListGroupEnum.APPROVAL.getCode()))) {
            // 审批中分组筛选条件
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(),"",FieldTypeEnum.FLOW_STATUS.getType(),ConditionEnum.IN.getSymbol(),Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(),FlowStatusEnum.IN_APPROVAL.getType()));
            formDataListDTO.getConditions().add(conditionsEntityExt);
        } else {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(), "", FieldTypeEnum.FLOW_STATUS.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
            formDataListDTO.getConditions().add(conditionsEntityExt);
        }
    }

    /**
     * 筛选已删除的工单模板
     *
     * @param formDataListDTO 查询入参
     * @param loginUser 登录员工
     * @author 徐俊杰
     * @date 2019/7/6 16:01
     * @since v1.0
     */
    private void filterDeleteForm(FormDataListDTO formDataListDTO, UserVO loginUser) {
        PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.WORK_ORDER.getAlias(), loginUser.getCorpid());
        if (paasAppEntity == null) {
            return;
        }
        Long appId = paasAppEntity.getId();
        appId = appId == null ? -1 : appId;
        List<WorkOrderFormEntity> workOrderFormEntities = workOrderFormService.getTemplateWithPermission(loginUser, appId, null);
        List<Long> workOrderFormIds = new ArrayList<>();
        for (WorkOrderFormEntity workOrderFormEntity : workOrderFormEntities) {
            workOrderFormIds.add(workOrderFormEntity.getId());
        }
        formDataListDTO.setFormIdList(workOrderFormIds);
    }

    private void filterWorkOrderStatus(FormDataListDTO formDataListDTO) {
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.WORK_ORDER_STATUS.getAlias(),"",FieldTypeEnum.WORK_ORDER_STATUS.getType(),ConditionEnum.IN.getSymbol(),Arrays.asList(WorkOrderStatusEnum.UNACCEPTED.getCode(),WorkOrderStatusEnum.ONGOING.getCode()));
        formDataListDTO.getConditions().add(conditionsEntityExt);
    }

    private void timeOutCondition(List<ConditionsEntityExt> conditions, Integer defaultGroup, Long listGroupId, String corpid,String userId) {
        Boolean isOut = null;
        for (ConditionsEntityExt entityExt : conditions){
            if (Objects.equals(entityExt.getFieldType(),FieldTypeEnum.WORK_ORDER_TIME_OUT.getType())){
                isOut = Objects.equals(entityExt.getValue().get(0),1);
                break;
            }
        }
        if (Objects.isNull(isOut)){
            return;
        }
        //是否是节点超时
        Boolean nodeTime = Objects.equals(defaultGroup,1) && (Objects.equals(listGroupId,(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_ME.getCode()) || Objects.equals(listGroupId,(long)ListGroupEnum.WORK_ORDER_RESPONSE_BY_SUB.getCode()));
        //人员限制一下,下属XXX获取下属员工；我XXX获取操作人；自定义及全部获取所有；对应工单或节点
        List<String> userIdIn = new ArrayList<>();
        List<Long> workOrderIdList = new ArrayList<>();
        if (nodeTime){

        }
        if (nodeTime) {
             workOrderIdList = workOrderFlowNodeModel.getTimeOutNode(corpid,Collections.singletonList("16"),isOut);
        }
        if (workOrderIdList.isEmpty()){
            workOrderIdList.add(-1L);
        }
        //超时工单
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityExt.setValue(new ArrayList<>(workOrderIdList));
        conditions.add(conditionsEntityExt);
    }

    private void setListColumn(FormDataListDTO formDataListDTO) {
        String defaultSortConfigAlias = UserConfigEnum.DEFAULT_SORT_FIELD.getAlias() + "_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
        String columnInvisibleConfigAlias = UserConfigEnum.COLUMN_INVISIBLE_FIELD.getAlias() + "_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",formDataListDTO.getCorpid());
        map.put("appId",formDataListDTO.getAppId());
        map.put("formId",formDataListDTO.getFormId());
        map.put("userId", formDataListDTO.getUserId());
        map.put("del",0);
        List<String> configAliasList = new ArrayList<>();
        configAliasList.add(defaultSortConfigAlias);
        configAliasList.add(columnInvisibleConfigAlias);
        map.put("configAliasIn", configAliasList);
        List<UserConfigEntity> userConfigList = userConfigModel.list(map);
        for (UserConfigEntity userConfigEntity : userConfigList){
            if (Objects.equals(userConfigEntity.getConfigAlias(),defaultSortConfigAlias)){
                Map<String,String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                JSONObject sort = JSONObject.parseObject(userConfigEntity.getConfigValue());
                sortMap.put("sort",sort.getString("sortType"));
                sortMap.put("field",sort.getString("sortAttr"));
                formDataListDTO.setSortMap(sortMap);
            }
        }
    }

    @Override
    public WorkOrderDataEsListVO robList(FormDataListDTO formDataListDTO) throws XbbException{
        //增加抢单查询es参数
        List<ConditionsEntityExt> conditionsEntityExtList;
        if (Objects.isNull(formDataListDTO.getConditions())) {
            conditionsEntityExtList = new ArrayList<>();
        } else {
            conditionsEntityExtList = new ArrayList<>(formDataListDTO.getConditions());
        }
        ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.ROB.getCode()));
        conditionsEntityExtList.add(conditionsEntityExt);
        formDataListDTO.setConditions(conditionsEntityExtList);
        workOrderListDataPermissionHelp.robListDataPermission(formDataListDTO.getConditions(), formDataListDTO.getLoginUser(), formDataListDTO.getLoginUser().getDepSet());
//        WorkOrderDataEsListVO workOrderDataEsListVO = list(formDataListDTO);
//        UserVO userVO = formDataListDTO.getLoginUser();
//        String corpid = formDataListDTO.getCorpid();
//        String userId = formDataListDTO.getUserId();
//        List<WorkOrderEntityExt> workOrderEntityExts = workOrderDataEsListVO.getPaasFormDataESList();
//        //过滤抢单工单（抄送人的工单）
//        if (!userVO.isAdminOrBossOrWorkOrderManager()) {
//            workOrderEntityExts = filterCcWorkOrder(workOrderEntityExts, corpid, userId);
//        }
//        workOrderDataEsListVO.setPaasFormDataESList(workOrderEntityExts);
//        return workOrderDataEsListVO;
        return list(formDataListDTO);
    }
    @Override
    public WorkOrderDataEsListVO normalList(FormDataListDTO formDataListDTO) throws XbbException{
        //增加抢单查询es参数
        List<ConditionsEntityExt> conditionsEntityExtList;
        if (Objects.isNull(formDataListDTO.getConditions())) {
            conditionsEntityExtList = new ArrayList<>();
        } else {
            conditionsEntityExtList = new ArrayList<>(formDataListDTO.getConditions());
        }
        ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.NORMAL.getCode()));
        conditionsEntityExtList.add(conditionsEntityExt);

        formDataListDTO.setConditions(conditionsEntityExtList);
        workOrderListDataPermissionHelp.listDataPermission(formDataListDTO.getConditions(),formDataListDTO.getShouldConditions(), formDataListDTO.getLoginUser(),formDataListDTO.getDefaultGroup(),formDataListDTO.getListGroupId());
        return list(formDataListDTO);
    }


    @Override
    public WorkOrderProcessVO progress(WorkOrderProgressDTO workOrderProgressDTO) throws XbbException {
        String corpid = workOrderProgressDTO.getCorpid();
        Long workOrderId = workOrderProgressDTO.getDataId();
        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(workOrderId,corpid);
        if (Objects.isNull(workOrderEntity) || workOrderEntity.getDel() == 1){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        Long templateId = workOrderEntity.getTemplateId();
        WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(templateId, corpid);
        //不限时自由工单
        boolean unLimit = Objects.equals(workOrderTemplateEntity.getIsFree(), 1) && Objects.equals(workOrderTemplateEntity.getExpectedTime(), 0);
        Map<Long,String> stageNameMap = workOrderStageService.getSatgeNameMap(templateId,corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer page = workOrderProgressDTO.getPage();
        Integer pageSize = workOrderProgressDTO.getPageSize();
        param.put("corpid",corpid);
        param.put("workOrderId",workOrderProgressDTO.getDataId());
        param.put("del",0);
        param.put("orderByStr","add_time desc,id desc");
        param.put("startGroup", (page - 1) * pageSize);
        param.put("pageNumGroup", pageSize);
        List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.findEntitys(param);
        List<WorkOrderNodeInfoPojo> workOrderNodeInfoPojoList = new ArrayList<>();
        String oldUserName = "";
        Long lastStartTime = 0L;
        Long freeOutTime = workOrderEntity.getStartTime() + workOrderEntity.getExpectedTime();
        Map<Long,Integer> expectedTimeMap = workOrderStageService.getExpectedTimeMap(corpid,workOrderEntity.getTemplateId());
        for (WorkOrderFlowNodeEntity entity : workOrderFlowNodeEntityList){
            WorkOrderNodeInfoPojo workOrderNodeInfoPojo = new WorkOrderNodeInfoPojo();
            List<WorkOrderProcessPojo> workOrderProcessPojoList = new ArrayList<>();
            workOrderNodeInfoPojo.setAddTime(entity.getAddTime());
            workOrderNodeInfoPojo.setAddTimeStr(DateTimeUtil.getStringEpochSecond(entity.getAddTime()));
            workOrderNodeInfoPojo.setStatus(entity.getStatus());
            workOrderNodeInfoPojo.setStatusName(WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            workOrderNodeInfoPojo.setStage(stageNameMap.getOrDefault(entity.getStageId(),""));
            workOrderNodeInfoPojo.setMemo(entity.getMemo());
            getStartProcess(workOrderProcessPojoList,entity);
            getEndProcess(workOrderProcessPojoList,entity,oldUserName);
            String outTimeMsg = getOutProcess(workOrderProcessPojoList,entity,freeOutTime,lastStartTime,expectedTimeMap.getOrDefault(entity.getStageId(),0),workOrderEntity.getEndTime(), unLimit);
            workOrderNodeInfoPojo.setProcessList(workOrderProcessPojoList);
            workOrderNodeInfoPojo.setOutTimeMsg(outTimeMsg);
            UserSimpPojo userSimpPojo = new UserSimpPojo();
            userSimpPojo.setName(entity.getUserName());
            userSimpPojo.setUserId(entity.getUserId());
            userSimpPojo.setUserAvatar(entity.getUserAvatar());
            workOrderNodeInfoPojo.setUser(userSimpPojo);
            workOrderNodeInfoPojoList.add(workOrderNodeInfoPojo);
            oldUserName = entity.getUserName();
            lastStartTime = entity.getStartTime();
        }
        param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("workOrderId",workOrderId);
        Integer count = workOrderFlowNodeModel.getEntitysCount(param);
        if (count + 1 > (page - 1) * pageSize && count + 1 <= page * pageSize){
            WorkOrderNodeInfoPojo workOrderNodeInfoPojo = new WorkOrderNodeInfoPojo();
            workOrderNodeInfoPojo.setAddTime(workOrderEntity.getAddTime());
            workOrderNodeInfoPojo.setAddTimeStr(DateTimeUtil.getStringEpochSecond(workOrderEntity.getAddTime()));
            UserEntity userEntity = userModel.getByKeyIngoreDel(workOrderEntity.getCreatorId(),workOrderEntity.getCorpid());
            UserSimpPojo userSimpPojo = new UserSimpPojo();
            userSimpPojo.setName(Objects.nonNull(userEntity) ? userEntity.getName() : "");
            userSimpPojo.setUserId(Objects.nonNull(userEntity) ? userEntity.getUserId() : "");
            userSimpPojo.setUserAvatar(Objects.nonNull(userEntity) ? userEntity.getAvatar() : "");
            WorkOrderProcessPojo workOrderProcessPojo = new WorkOrderProcessPojo();
            workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(workOrderEntity.getAddTime()));
            workOrderProcessPojo.setContent(String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.CREATE_WORKORDER),Objects.nonNull(userEntity) ? userEntity.getName() : ""));
            workOrderNodeInfoPojo.setProcessList(Collections.singletonList(workOrderProcessPojo));
            UserSimpPojo userPojo = new UserSimpPojo();
            userPojo.setUserAvatar(Objects.nonNull(userEntity) ? userEntity.getAvatar() : "");
            userPojo.setUserId(Objects.nonNull(userEntity) ? userEntity.getUserId() : "");
            userPojo.setName(Objects.nonNull(userEntity) ? userEntity.getName() : "");
            workOrderNodeInfoPojo.setUser(userPojo);
            workOrderNodeInfoPojoList.add(workOrderNodeInfoPojo);
        }
        WorkOrderProcessVO workOrderProcessVO = new WorkOrderProcessVO();
        workOrderProcessVO.setList(workOrderNodeInfoPojoList);
        PageHelper pageHelper = new PageHelper(page,pageSize);
        pageHelper.setRowsCount(count + 1);
        workOrderProcessVO.setPageHelper(pageHelper);
        return workOrderProcessVO;
    }

    @Override
    public WorkOrderMyPendingVO getMyPendingWorkOrderList(WorkOrderMyPendingDTO workOrderMyPendingDTO) throws XbbException {
        String userId = workOrderMyPendingDTO.getUserId();
        String corpid = workOrderMyPendingDTO.getCorpid();
        WorkOrderMyPendingVO workOrderMyPendingVO = new WorkOrderMyPendingVO();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(workOrderMyPendingDTO, formDataListDTO);
        //增加代抢单单查询es参数
        List<ConditionsEntityExt> robConditions = new ArrayList<>();
        List<List<ConditionsEntityExt>> shouldConditions = new ArrayList<>();
        ConditionsEntityExt typeConditionsEntityExt = new ConditionsEntityExt();
        typeConditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        typeConditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        typeConditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        typeConditionsEntityExt.setValue(Collections.singletonList(1));
        robConditions.add(typeConditionsEntityExt);
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(workOrderMyPendingDTO.getLoginUser(),userEntity);
        workOrderListDataPermissionHelp.robListDataPermission(robConditions, workOrderMyPendingDTO.getLoginUser(), workOrderMyPendingDTO.getLoginUser().getDepSet());
        shouldConditions.add(robConditions);
        //conditionsEntityExts用于下面加入审批筛选的es条件
        List<ConditionsEntityExt> conditionsEntityExts = new ArrayList<>();
        //增加普通工单查询es参数
        List<ConditionsEntityExt> conditionsEntityExtList;
        if (Objects.isNull(formDataListDTO.getConditions())) {
            conditionsEntityExtList = new ArrayList<>();
        } else {
            conditionsEntityExtList = new ArrayList<>(formDataListDTO.getConditions());
        }
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
        conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityExt.setValue(Collections.singletonList(0));
        conditionsEntityExtList.add(conditionsEntityExt);
        //增加（待接受，进行）查询es参数
        ConditionsEntityExt conditionsEntityExt1 = new ConditionsEntityExt();
        conditionsEntityExt1.setAttr(FieldTypeEnum.WORK_ORDER_STATUS.getAlias());
        conditionsEntityExt1.setFieldType(FieldTypeEnum.WORK_ORDER_STATUS.getType());
        conditionsEntityExt1.setSymbol(ConditionEnum.IN.getSymbol());
        List<Object> list1 = new ArrayList<>();
        list1.add(WorkOrderNodeStatusEnum.UNACCEPTED.getCode());
        list1.add(WorkOrderNodeStatusEnum.ONGOING.getCode());
        conditionsEntityExt1.setValue(list1);
        conditionsEntityExtList.add(conditionsEntityExt1);

        //增加（负责人（协同人团队表））查询es参数
        UserVO userVO = workOrderMyPendingDTO.getLoginUser();
        /*if (userVO.isAdminOrBossOrWorkOrderManager()) {
            ConditionsEntityExt conditionsEntityExt2 = new ConditionsEntityExt();
            conditionsEntityExt2.setAttr(FieldTypeEnum.OWNERID.getAlias());
            conditionsEntityExt2.setFieldType(10017);
            conditionsEntityExt2.setSymbol(ConditionEnum.EQUAL.getSymbol());
            UserEntity userEntity = BeanUtil.copyProperties(userVO, UserEntity.class, false);
            List userIdIn = userModel.getSubIdList(userEntity, true, 1, false);
            conditionsEntityExt2.setValue((List<Object>) userIdIn);
            conditionsEntityExtList.add(conditionsEntityExt2);
            shouldConditions.add(conditionsEntityExtList);
        } else {
            ConditionsEntityExt conditionsEntityExt2 = new ConditionsEntityExt();
            conditionsEntityExt2.setAttr(FieldTypeEnum.OWNERID.getAlias());
            conditionsEntityExt2.setFieldType(10017);
            conditionsEntityExt2.setSymbol(ConditionEnum.EQUAL.getSymbol());
            conditionsEntityExt2.setValue(Collections.singletonList(userId));
            conditionsEntityExtList.add(conditionsEntityExt2);
            shouldConditions.add(conditionsEntityExtList);
        }*/
        ConditionsEntityExt conditionsEntityExt2 = new ConditionsEntityExt();
        conditionsEntityExt2.setAttr(FieldTypeEnum.OWNERID.getAlias());
        conditionsEntityExt2.setFieldType(10017);
        conditionsEntityExt2.setSymbol(ConditionEnum.EQUAL.getSymbol());
        conditionsEntityExt2.setValue(Collections.singletonList(userId));
        conditionsEntityExtList.add(conditionsEntityExt2);
        shouldConditions.add(conditionsEntityExtList);
        formDataListDTO.setShouldConditions(shouldConditions);
        formDataListDTO.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
        formDataListDTO.setConditions(conditionsEntityExts);
        //过滤审批中数据
        filterApprovalData(formDataListDTO);
        //过滤已删除工单模板
        filterDeleteForm(formDataListDTO, userVO);
        //过滤工单状态
        //filterWorkOrderStatus(formDataListDTO);
        WorkOrderDataEsListVO workOrderDataEsListVO = paasFormDataEsModel.workOrderList(formDataListDTO);
        List<WorkOrderEntityExt> workOrderEntityExts = workOrderDataEsListVO.getPaasFormDataESList();
        List<Long> workOrderIdIn = new ArrayList<>();
        for (WorkOrderEntityExt workOrderEntityExt : workOrderEntityExts) {
            Long workOrderId = workOrderEntityExt.getId();
            workOrderIdIn.add(workOrderId);
        }
        if (userVO.isAdminOrBossOrWorkOrderManager()) {
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WORK_ORDER.getCode(), null);
            List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(), BasicConstant.ONE, false);
            List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.getWorkOrderFlowStatus1(corpid, workOrderIdIn, userIdIn);
            if (workOrderFlowNodeEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404.getCode(), SystemErrorCodeEnum.API_ERROR_100404.getMsg());
            }
            for (WorkOrderFlowNodeEntity workOrderFlowNodeEntity : workOrderFlowNodeEntityList) {
                Long id = workOrderFlowNodeEntity.getWorkOrderId();
                for (WorkOrderEntityExt workOrderEntityExt : workOrderEntityExts) {
                    if (workOrderEntityExt.getId().equals(id)) {
                        workOrderEntityExt.setNodeStatus(workOrderFlowNodeEntity.getStatus());
                    }
                }
            }
        } else {
            List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.getWorkOrderFlowStatus(corpid, workOrderIdIn, userId);
            if (workOrderFlowNodeEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404.getCode(), SystemErrorCodeEnum.API_ERROR_100404.getMsg());
            }
            for (WorkOrderFlowNodeEntity workOrderFlowNodeEntity : workOrderFlowNodeEntityList) {
                Long id = workOrderFlowNodeEntity.getWorkOrderId();
                for (WorkOrderEntityExt workOrderEntityExt : workOrderEntityExts) {
                    if (workOrderEntityExt.getId().equals(id)) {
                        workOrderEntityExt.setNodeStatus(workOrderFlowNodeEntity.getStatus());
                    }
                }
            }
        }
        String title;
        JSONObject data = new JSONObject();
        List<MyPendingDataVO> list = new ArrayList<>();
        for (WorkOrderEntityExt entityExt : workOrderEntityExts) {
            data = entityExt.getData();
            //若工单名称为空的情况，就赋值为工单编号
            if (data.containsKey(WorkOrderEnum.NAME.getAttr()) && data.get(WorkOrderEnum.NAME.getAttr()) != null) {
                String attr = WorkOrderEnum.NAME.getAttr();
                Object value = data.get(attr);
                title = value.toString();
            } else {
                title = entityExt.workOrderName();
            }
            MyPendingDataVO myPendingDataVO = new MyPendingDataVO();
            myPendingDataVO.setMenuId(entityExt.getMenuId());
            myPendingDataVO.setFormId(entityExt.getFormId());
            myPendingDataVO.setAppId(entityExt.getAppId());
            myPendingDataVO.setTitle(title);
            myPendingDataVO.setWorkOrderId(entityExt.getId());
            myPendingDataVO.setWorkOrderNo(entityExt.getSerialNo());
            String stageName = "";
            if (!Objects.isNull(data.get(WorkOrderEnum.STAGE_NAME.getAttr()))) {
                stageName = data.get(WorkOrderEnum.STAGE_NAME.getAttr()).toString();
            }
            myPendingDataVO.setStateName(stageName);
            //获取解释
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(entityExt.getFormId(), corpid);
            if (workOrderExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
            //抢单工单没有负责人
            if (entityExt.getType() == 0) {
                Map<Long,String> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long,String> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                userTeamService.getUserMap(workOrderIdIn,corpid,XbbRefTypeEnum.WORK_ORDER.getCode(),false,mainUserMap,coUserMap);
                Integer visible = null;
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), WorkOrderEnum.OWNER_ID.getAttr())) {
                        //获取负责人是否可见
                        visible = fieldAttrEntity.getVisible();
                    }
                }
                //负责人不可见时变--
                if (Objects.equals(visible, BasicConstant.ZERO)) {
                    myPendingDataVO.setUserName("--");
                } else {
                    myPendingDataVO.setUserName(mainUserMap.getOrDefault(entityExt.getDataId(),""));
                }

            } else {
                myPendingDataVO.setUserName("");
            }
            myPendingDataVO.setAddTime(entityExt.getAddTime());

            WorkOrderProcessNodeV0 workOrderProcessNodeV0 = new WorkOrderProcessNodeV0();
            List<WorkOrderProcessOperateVO> processOperate = new ArrayList<>();
            WorkOrderProcessOperateVO processOperateVo1 = new WorkOrderProcessOperateVO();
            if (Objects.equals(entityExt.getNodeStatus(), WorkOrderStatusEnum.UNACCEPTED.getCode())) {
                processOperateVo1.setFlag(1);
                processOperateVo1.setText(WorkOrderStageOperationEnum.ACCEPT.getName());
                processOperateVo1.setType(WorkOrderStageOperationEnum.ACCEPT.getCode());
                processOperateVo1.setOperate(WorkOrderStageOperationEnum.ACCEPT.getAlias());
                processOperate.add(processOperateVo1);
            } else {
                processOperateVo1.setFlag(1);
                processOperateVo1.setText(WorkOrderStageOperationEnum.COMPLETE.getName());
                processOperateVo1.setType(WorkOrderStageOperationEnum.COMPLETE.getCode());
                processOperateVo1.setOperate(WorkOrderStageOperationEnum.COMPLETE.getAlias());
                processOperate.add(processOperateVo1);
            }
            WorkOrderProcessOperateVO processOperateVo2 = new WorkOrderProcessOperateVO();
            processOperateVo2.setFlag(1);
            processOperateVo2.setText(WorkOrderStageOperationEnum.CLOSE.getName());
            processOperateVo2.setType(WorkOrderStageOperationEnum.CLOSE.getCode());
            processOperateVo2.setOperate(WorkOrderStageOperationEnum.CLOSE.getAlias());
            processOperate.add(processOperateVo2);
            workOrderProcessNodeV0.setProcessOperate(processOperate);
            myPendingDataVO.setProcessOperatePermission(workOrderProcessNodeV0);
            list.add(myPendingDataVO);
        }
        workOrderMyPendingVO.setList(list);
        workOrderMyPendingVO.setTotalCount(workOrderDataEsListVO.getPageHelper().getRowsCount());
        return workOrderMyPendingVO;
    }

    /**
     * 获取工单打印相关的数据(工单进展,工单进展抄送人,工单动态,工单动态评论)
     * @param formDataGetDTO
     * @return
     * @throws XbbException
     */
    @Override
    public JSONObject getPrintRelationData(FormDataGetDTO formDataGetDTO) throws XbbException {
        JSONObject printRelationData = new JSONObject();
        Long dataId = formDataGetDTO.getDataId();
        String corpid = formDataGetDTO.getCorpid();
        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId,corpid);
        if (Objects.isNull(workOrderEntity) || workOrderEntity.getDel() == 1){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        // 获取工单进展
        getWorkOrderProcess(printRelationData, dataId, corpid, workOrderEntity);
        // 获取工单抄送人
        List<String> userIds = workOrderCcModel.getUserIds(corpid, dataId);
        List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, userIds, true);
        List<String> userName = new ArrayList<>();
        for (UserEntity entity : userEntities) {
            userName.add(entity.getName());
        }
        // workOrderProgress
        printRelationData.getJSONObject("workOrderProgress").put("workOrderCCList",userName);
        // workOrderProgress.;
        // printRelationData.put("workOrderCCList",userName);
        return printRelationData;
    }

    /**
     * 获取工单进展(已转换成打印专用格式)
     * @param printRelationData
     * @param dataId
     * @param corpid
     * @param workOrderEntity
     */
    private void getWorkOrderProcess(JSONObject printRelationData, Long dataId, String corpid, WorkOrderEntity workOrderEntity) {
        List<JSONObject> list = new ArrayList<>();
        Long templateId = workOrderEntity.getTemplateId();
        WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(templateId, corpid);
        boolean unLimit = Objects.equals(workOrderTemplateEntity.getIsFree(), 1) && Objects.equals(workOrderTemplateEntity.getExpectedTime(), 0);
        Map<Long,String> stageNameMap = workOrderStageService.getSatgeNameMap(templateId,corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("workOrderId",dataId);
        param.put("del",0);
        param.put("orderByStr","add_time desc,id desc");
        List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntityList = workOrderFlowNodeModel.findEntitys(param);
        String oldUserName = "";
        Long lastStartTime = 0L;
        Long freeOutTime = workOrderEntity.getStartTime() + workOrderEntity.getExpectedTime();
        Map<Long,Integer> expectedTimeMap = workOrderStageService.getExpectedTimeMap(corpid,workOrderEntity.getTemplateId());
        for (WorkOrderFlowNodeEntity entity : workOrderFlowNodeEntityList){
            JSONObject detail = new JSONObject();
            detail.put("addTimeStr", DateTimeUtil.getStringEpochSecond(entity.getAddTime()));
            detail.put("status",entity.getStatus());
            detail.put("statusName", WorkOrderNodeStatusEnum.getByCode(entity.getStatus()).getName());
            detail.put("stage",stageNameMap.getOrDefault(entity.getStageId(),""));
            List<WorkOrderProcessPojo> workOrderProcessPojoList = new ArrayList<>();
            getStartProcess(workOrderProcessPojoList,entity);
            getEndProcess(workOrderProcessPojoList,entity,oldUserName);
            String outTimeMsg = getOutProcess(workOrderProcessPojoList,entity,freeOutTime,lastStartTime,expectedTimeMap.getOrDefault(entity.getStageId(),0),workOrderEntity.getEndTime(), unLimit);
            detail.put("outTimeMsg",outTimeMsg);
            detail.put("memo",entity.getMemo());
            detail.put("userName",entity.getUserName());
            detail.put("processList",workOrderProcessPojoList);
            oldUserName = entity.getUserName();
            list.add(detail);
        }
        // 添加工单创建人
        JSONObject createWorkOrder = new JSONObject();
        createWorkOrder.put("addTimeStr",DateTimeUtil.getStringEpochSecond(workOrderEntity.getAddTime()));
        createWorkOrder.put("status",0);
        UserEntity userEntity = userModel.getByKeyIngoreDel(workOrderEntity.getCreatorId(),workOrderEntity.getCorpid());
        // 因为打印开始工单动态特殊设置statusName 存储content内容
        createWorkOrder.put("statusName",String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.CREATE_WORKORDER),Objects.isNull(userEntity) ? "" : userEntity.getName()));
        createWorkOrder.put("stage",I18nMessageUtil.getMessage(MessageConstant.DISPATCH_LIST));
        createWorkOrder.put("userName",Objects.isNull(userEntity) ? "" : userEntity.getName());
        // WorkOrderProcessPojo workOrderProcessPojo = new WorkOrderProcessPojo();
        // workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(workOrderEntity.getAddTime()));
        // workOrderProcessPojo.setContent(String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.CREATE_WORKORDER),userEntity.getName()));
        // List<WorkOrderProcessPojo> createWorkOrderList = new ArrayList<>();
        // createWorkOrderList.add(workOrderProcessPojo);
        // createWorkOrder.put("processList",createWorkOrderList);
        list.add(createWorkOrder);
        JSONObject process = new JSONObject();
        process.put("progress",list);
        printRelationData.put("workOrderProgress",process);
    }

    /**
     * 超时
     * @param workOrderProcessPojoList
     * @param entity 节点
     * @param freeOutTime 自由流程超时时间点
     * @param lastStartTime 上次节点开始时间 自由是0，不用这个
     * @param expectedTime 预计完成时间
     * @param workOrderEndTime 工单完成时间
     * @param unLimit 自由不限时工单
     */
    private String getOutProcess(List<WorkOrderProcessPojo> workOrderProcessPojoList, WorkOrderFlowNodeEntity entity, Long freeOutTime, Long lastStartTime, Integer expectedTime, Long workOrderEndTime, boolean unLimit) {
        if (Objects.equals(entity.getStartTime(),0L)){
            return "";
        }
        if (Objects.equals(entity.getStatus(),WorkOrderNodeStatusEnum.RESTART.getCode())){
            return "";
        }
        WorkOrderProcessPojo workOrderProcessPojo = new WorkOrderProcessPojo();
        String outTimeMsg = "";
        String content;
        Boolean isFree = entity.getStageId() == 0;
        Integer actualTime = entity.getActualTime();
        actualTime = entity.getEndTime() == 0 ? (int)(DateTimeUtil.getInt() - entity.getStartTime()) : actualTime;
        workOrderEndTime = workOrderEndTime == 0L ? DateTimeUtil.getInt() : workOrderEndTime;
        if (isFree){
            if (unLimit) {
                return "";
            }
            Long endTime = entity.getEndTime() == 0 ? DateTimeUtil.getInt() : entity.getEndTime();
            if (entity.getStartTime() <= freeOutTime && endTime >= freeOutTime){
                //超时时间在开始与结束之间
                workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(entity.getStartTime() + expectedTime));
                content = I18nMessageUtil.getMessage(WorkOrderProcessConstant.OUTTIME_FREE_PROCESS);
                workOrderProcessPojo.setContent(content);
                workOrderProcessPojo.setIsOut(true);
                workOrderProcessPojoList.add(1,workOrderProcessPojo);
                outTimeMsg = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.FREE_OUTTIME),TimeUtil.getString((int)(workOrderEndTime - freeOutTime)));
            }else if (lastStartTime > freeOutTime && endTime < freeOutTime){
                //超时时间在两个节点间
                workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(entity.getStartTime() + expectedTime));
                content = I18nMessageUtil.getMessage(WorkOrderProcessConstant.OUTTIME_FREE_PROCESS);
                workOrderProcessPojo.setContent(content);
                workOrderProcessPojo.setIsOut(true);
                workOrderProcessPojoList.add(workOrderProcessPojo);
                outTimeMsg = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.FREE_OUTTIME),TimeUtil.getString((int)(workOrderEndTime - freeOutTime)));
            }else {
                return outTimeMsg;
            }
        }else {
            if (actualTime <= expectedTime){
                return "";
            }
            workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(entity.getStartTime() + expectedTime));
            content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.OUTTIME_PROCESS),entity.getStageName());
            workOrderProcessPojo.setContent(content);
            workOrderProcessPojo.setIsOut(true);
            workOrderProcessPojoList.add(1,workOrderProcessPojo);
            outTimeMsg = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.OUTTIME),entity.getStageName(),TimeUtil.getString(actualTime - expectedTime));
        }
        return outTimeMsg;
    }

    /**
     * 结束
     * @param workOrderProcessPojoList
     * @param entity
     * @param oldUserName
     */
    private void getEndProcess(List<WorkOrderProcessPojo> workOrderProcessPojoList, WorkOrderFlowNodeEntity entity, String oldUserName) {
        WorkOrderProcessPojo workOrderProcessPojo = new WorkOrderProcessPojo();
        if (Objects.equals(entity.getEndTime(),0L)){
            return;
        }
        workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(entity.getEndTime()));
        String content = "";
        Integer status = entity.getStatus();
        WorkOrderNodeStatusEnum workOrderStatusEnum = WorkOrderNodeStatusEnum.getByCode(status);
        Boolean isFree = entity.getStageId() == 0;
        switch (workOrderStatusEnum){
            case FINISH:
                if (isFree){
                    if (entity.getEndOperatorName().isEmpty()){
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.FINISH_FREE_PROCESS),entity.getUserName());
                    }else {
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_FREE_FINISH),entity.getEndOperatorName(),entity.getUserName());
                    }
                }else {
                    if (entity.getEndOperatorName().isEmpty()){
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.FINISH_PROCESS),entity.getUserName(),entity.getStageName());
                    }else {
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_FINISH),entity.getEndOperatorName(),entity.getUserName(),entity.getStageName());
                    }
                }
                break;
            case TRANSFERRED:
                if (entity.getEndOperatorName().isEmpty()){
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.TRANSFER_PROCESS),entity.getUserName(),oldUserName);
                }else {
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_TRANSFER),entity.getEndOperatorName(),entity.getUserName(),oldUserName);
                }
                break;
            case ROLLBACK:
                if (entity.getEndOperatorName().isEmpty()){
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.ROLLBACK_PROCESS),entity.getUserName());
                }else {
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_ROLLBACK),entity.getEndOperatorName(),entity.getUserName());
                }
                break;
            case CLOSE:
                if (entity.getEndOperatorName().isEmpty()){
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.CLOSE_PROCESS),entity.getUserName());
                }else {
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.CLOSE_PROCESS),entity.getEndOperatorName());
                }
                break;
            default:
                return;
        }
        workOrderProcessPojo.setContent(content);
        workOrderProcessPojoList.add(workOrderProcessPojo);
    }

    /**
     * 节点开始进展信息
     * 待接收
     * 关闭
     * 重启
     * 其他所有
     * @param workOrderProcessPojoList
     * @param entity
     */
    private void getStartProcess(List<WorkOrderProcessPojo> workOrderProcessPojoList, WorkOrderFlowNodeEntity entity) {
        WorkOrderProcessPojo workOrderProcessPojo = new WorkOrderProcessPojo();
        workOrderProcessPojo.setTime(DateTimeUtil.getStringEpochSecond(entity.getStartTime()));
        String content = "";
        Integer status = entity.getStatus();
        WorkOrderNodeStatusEnum workOrderStatusEnum = WorkOrderNodeStatusEnum.getByCode(status);
        switch (workOrderStatusEnum){
            case UNACCEPTED:
                if (entity.getNodeType() == 1){
                    String robTypeStr = "";
                    String robName = "";
                    if (Objects.equals(entity.getRobType(),WorkOrderStageRobTypeEnum.SERVICE.getCode())){
                        robTypeStr = WorkOrderStageRobTypeEnum.SERVICE.getName();
                        WorkOrderTagEntity workOrderTagEntity = workOrderTagModel.getByKey(Long.valueOf(entity.getRobId()),entity.getCorpid());
                        robName = Objects.nonNull(workOrderTagEntity) ? workOrderTagEntity.getName() : robName;
                    }else  if (Objects.equals(entity.getRobType(),WorkOrderStageRobTypeEnum.DEPARTMENT.getCode())){
                        robTypeStr = WorkOrderStageRobTypeEnum.DEPARTMENT.getName();
                        DepartmentEntity departmentEntity = departmentModel.getByKey(Long.valueOf(entity.getRobId()),entity.getCorpid());
                        robName = Objects.nonNull(departmentEntity) ? departmentEntity.getName() : robName;
                    }
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.UNACCPET_ROB_PROCESS),robName,robTypeStr);
                }else {
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.UNACCPET_PROCESS),entity.getUserName());
                }
                break;
            case CLOSE:
                if (entity.getNodeType() == 1){
                    String robName = "";
                    String robTypeStr = "";
                    if (Objects.equals(entity.getRobType(),WorkOrderStageRobTypeEnum.SERVICE.getCode())){
                        robTypeStr = WorkOrderStageRobTypeEnum.SERVICE.getName();
                        WorkOrderTagEntity workOrderTagEntity = workOrderTagModel.getByKey(Long.valueOf(entity.getRobId()),entity.getCorpid());
                        robName = Objects.nonNull(workOrderTagEntity) ? workOrderTagEntity.getName() : robName;
                    }else  if (Objects.equals(entity.getRobType(),WorkOrderStageRobTypeEnum.DEPARTMENT.getCode())){
                        robTypeStr = WorkOrderStageRobTypeEnum.DEPARTMENT.getName();
                        DepartmentEntity departmentEntity = departmentModel.getByKey(Long.valueOf(entity.getRobId()),entity.getCorpid());
                        robName = Objects.nonNull(departmentEntity) ? departmentEntity.getName() : robName;
                    }
                    if (Objects.equals(entity.getStartTime(),0L)){
                        //抢单未开始
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.UNSTARTROB_PROCESS),robName,robTypeStr);
                    }else {
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.UNACCPET_ROB_PROCESS),robName,robTypeStr);
                    }
                }else {
                    if (Objects.equals(entity.getStartTime(),0L)){
                        content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.UNSTART_NODE),entity.getUserName());
                    }else {
                        if (entity.getStartOperatorName().isEmpty()){
                            content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.ACCEPT_PROCESS),entity.getUserName());
                        }else {
                            content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_ACCEPT),entity.getStartOperatorName(),entity.getUserName());
                        }
                    }
                }
                break;
            case RESTART:
                content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.RESTART_PROCESS),entity.getUserName());
                break;
            case ONGOING:
            case ROLLBACK:
            case TRANSFERRED:
            case FINISH:
                if (entity.getStartOperatorName().isEmpty()){
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.ACCEPT_PROCESS),entity.getUserName());
                }else {
                    content = String.format(I18nMessageUtil.getMessage(WorkOrderProcessConstant.INSTEAD_OF_ACCEPT),entity.getStartOperatorName(),entity.getUserName());
                }
                break;
            default:
                break;
        }
        workOrderProcessPojo.setContent(content);
        workOrderProcessPojoList.add(workOrderProcessPojo);
    }

    /**
     * 移动端列表页数据特殊处理
     *
     * @param workOrderDataEsListVO
     * @author long.rao
     * @date 2019-07-06 18:53
     */
    private void handlerAppList(WorkOrderDataEsListVO workOrderDataEsListVO) {
        List<WorkOrderEntityExt> paasFormDataESList = workOrderDataEsListVO.getPaasFormDataESList();
        if (paasFormDataESList.isEmpty()) {
            return;
        }
        for (WorkOrderEntityExt entityExt : paasFormDataESList) {
            JSONObject data = entityExt.getData();
            //实施地址
            String address = commentHelp.formatAddress(data, WorkOrderEnum.ADDRESS.getAttr());
            if (address != null) {
                data.put(WorkOrderEnum.ADDRESS.getAttr(), address);
            }
        }
        workOrderDataEsListVO.setPaasFormDataESList(paasFormDataESList);
    }

    /**
     * 处理表单冻结列，隐藏列
     * @param formDataListDTO FormDataListDTO
     * @param formDataListVO PaasFormDataEsListVO
     * @throws XbbException xbbException
     * @author 李少杰
     */
    public void setFixedAndInvisible(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {
        try {
            if (Objects.isNull(formDataListDTO.getFormId())) {
                // 全部列表的formId是0
                formDataListDTO.setFormId(0L);
            }
            ColumnSetListDTO columnSetListDTO = new ColumnSetListDTO();
            BeanUtil.copyProperties(formDataListDTO, columnSetListDTO);
            if (Objects.equals(columnSetListDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(columnSetListDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                // 个人配置接口，预警查询，保质期查询用的都是库存查询的
                columnSetListDTO.setSubBusinessType(XbbRefTypeEnum.STOCK_SEARCH.getCode());
                if (Objects.nonNull(formDataListDTO.getListGroupId())) {
                    columnSetListDTO.setGroupId(formDataListDTO.getListGroupId());
                }
            }
            ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
            Map<String, Object> userConfigMap = columnSetListVO.getUserConfigMap();
            if (userConfigMap != null) {
                //用户配置 隐藏列
                JSONArray invisibleField = JSONArray.parseArray(JSON.toJSONString(userConfigMap.getOrDefault(UserConfigEnum.COLUMN_INVISIBLE_FIELD.getAlias(), new JSONArray())));
                //用户配置 冻结列
                Integer fixNum = (Integer) userConfigMap.getOrDefault(UserConfigEnum.COLUMN_FIXED_FIELD.getAlias(), 0);
                List<FieldAttrEntity> visibleFieldAttrEntity = new ArrayList<>();
                List<FieldAttrEntity> headList = formDataListVO.getHeadList();
                headList.forEach(item-> {
                    //设置隐藏列
                    if (invisibleField.contains(item.getAttr())) {
                        item.setVisible(0);
                    } else {
                        visibleFieldAttrEntity.add(item);
                    }
                });
                if (fixNum >= visibleFieldAttrEntity.size()) {
                    fixNum = visibleFieldAttrEntity.size();
                }
                List<FieldAttrEntity> fixedFieldAttrEntity = visibleFieldAttrEntity.subList(0, fixNum);
                headList.forEach(item -> {
                    if (fixedFieldAttrEntity.contains(item)) {
                        item.setFixed(true);
                    }
                });
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("列表冻结发生异常：", e);
        }
    }

    /**
     * 处理列表页字段排序
     *
     * @param formDataListDTO
     * @param formDataListVO
     * @throws
     * @author long.rao
     * @date 2019-11-25 14:46
     */
    private void explainFieldSort(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException{
        if (Objects.isNull(formDataListDTO.getFormId())) {
            // 全部列表的formId是0
            formDataListDTO.setFormId(0L);
        }
        ColumnSetListDTO columnSetListDTO = new ColumnSetListDTO();
        BeanUtil.copyProperties(formDataListDTO, columnSetListDTO);
        ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
        Map<String, Object> userConfigMap = columnSetListVO.getUserConfigMap();
        if (userConfigMap != null) {
            JSONArray fieldSort = (JSONArray) userConfigMap.getOrDefault(UserConfigEnum.COLUMN_SORT_FIELD.getAlias(), new JSONArray());
            if (Objects.isNull(fieldSort) || fieldSort.isEmpty()) {
                return;
            }
            Map<String, Integer> attrAndSort = new HashMap<>(fieldSort.size());
            for (int i = 0; i < fieldSort.size(); i++) {
                JSONObject o = (JSONObject)fieldSort.get(i);
                attrAndSort.put(o.getString("attr"), o.getInteger("sort"));
            }
            List<FieldAttrEntity> headList = formDataListVO.getHeadList();
            headList.forEach(item-> {
                // 如果attrAndSort里没有，那么证明是新的字段，sort直接给它最大值
                item.setSort(attrAndSort.getOrDefault(item.getAttr(), headList.size()));
            });
            Collections.sort(headList, Comparator.comparingInt(FieldAttrEntity::getSort));
        }
    }

    /**
     * 设置范围筛选
     *
     * @param formDataListDTO
     * @throws
     * @author long.rao
     * @date 2020-03-03 14:13
     */
    private void rangeScreen(FormDataListDTO formDataListDTO) throws XbbException {
        JSONObject commonFilter = formDataListDTO.getCommonFilter();
        if (Objects.isNull(commonFilter)) {
            return;
        }
        JSONObject rangeScreen = commonFilter.getJSONObject(RangeScreenConstant.RANGE_SCREEN);
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        String attr;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
            attr = rangeScreen.getString(RangeScreenConstant.ATTR);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "saasListHelp.commonFilter中的commonFilter参数错误");
        }

        if (CollectionsUtil.isEmpty(values)) {
            return;
        }

        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, formDataListDTO.getCorpid(), 1, true);
        }

        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
        Integer fieldType = 0;
        if (Objects.equals(attr, WorkOrderEnum.OWNER_ID.getAttr())) {
            fieldType = WorkOrderEnum.OWNER_ID.getFieldType();
        } else if (Objects.equals(attr, WorkOrderEnum.COUSERID.getAttr())) {
            fieldType = WorkOrderEnum.COUSERID.getFieldType();
        } else if (Objects.equals(attr, WorkOrderEnum.CREATOR_ID.getAttr())) {
            fieldType = WorkOrderEnum.CREATOR_ID.getFieldType();
        }
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(attr, "", fieldType, ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
        conditionsEntityExtList.add(conditionsEntityExt);
    }
}
